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)
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)
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','root@example.com'], stdout=PIPE, stdin=PIPE)
p.stdin.write("ls\n")
print(p.stdout.read())
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.