1

I have to monitor 8 to 9 servers. I am thinking of creating a python script that will create a menu to login to any servers and after using ssh to login to the server, can I be able to execute commands in the server as the 'user' specified in the ssh. Please see the command below in python. I am importing 'os' to execute the bash commands.

 server_login = "ssh {}@{}".format('user_name','10.111.0.10')
            os.system(server_login)
1
  • 1
    Then instead of just ssh <user>@<host> do ssh <user>@<host> <command>. If you don't specify a command then it will do an interactive login. Commented Aug 4, 2020 at 5:37

2 Answers 2

3

you can install paramiko for this

pip install paramiko

then the script can be like


import paramiko

host = "google.com"
port = 22
username = "user"
password = "Pass"

command = "ls"

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, port, username, password)

stdin, stdout, stderr = ssh.exec_command(command)
lines = stdout.readlines()
print(lines)

Sign up to request clarification or add additional context in comments.

Comments

0

If paramiko isn't your style, I can think of two other ways to do this:

run the command: ssh <user>@<host> <command> for every command via os.system calls. This gets rather cumbersome when you're using passwords for SSH instead of keys.

run ssh <user>@<host> with the subprocess library instead so you can get access to stdin and stdout and run multiple commands in the session

import subprocess
p = subprocess.Popen(['ssh','[email protected]'], stdout=PIPE, stdin=PIPE)
p.stdin.write("ls\n")
print(p.stdout.read())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.