用Python执行ssh命令

我正在编写一个脚本来自动化Python中的一些命令行命令。 目前我正在打电话:

cmd = "some unix command" retcode = subprocess.call(cmd,shell=True) 

不过,我需要在远程机器上运行一些命令。 手动,我会使用SSHlogin,然后运行命令。 我怎么会在Python中自动化? 我需要使用(已知)密码login到远程机器,所以我不能只使用cmd = ssh user@remotehost ,我想知道是否有我应该使用的模块?

我会把你推荐给paramiko

看到这个问题

 ssh = paramiko.SSHClient() ssh.connect(server, username=username, password=password) ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(cmd_to_execute) 

或者你可以使用commands.getstatusoutput :

  commands.getstatusoutput("ssh machine 1 'your script'") 

我广泛使用它,它工作得很好。

在Python 2.6+中,使用subprocess.check_output。

你看过织物吗? 它允许你使用python通过SSH做各种远程的东西。

我发现paramiko有些太低级了,Fabric不太适合用作库,所以我把我自己的库叫做spur ,它使用paramiko来实现一个更好的接口:

 import spur shell = spur.SshShell(hostname="localhost", username="bob", password="password1") result = shell.run(["echo", "-n", "hello"]) print result.output # prints hello 

如果你需要在shell中运行:

 shell.run(["sh", "-c", "echo -n hello"]) 

所有已经陈述(推荐)使用paramiko ,我只是共享一个Python代码(API可以说),这将允许您一次执行多个命令。

在不同节点上执行命令使用: Commands().run_cmd(host_ip, list_of_commands)

你会看到一个TODO,如果任何一个命令执行失败,我都会停止执行,我不知道该怎么做。 请分享你的知识

 #!/usr/bin/python import os import sys import select import paramiko import time class Commands: def __init__(self, retry_time=0): self.retry_time = retry_time pass def run_cmd(self, host_ip, cmd_list): i = 0 while True: # print("Trying to connect to %s (%i/%i)" % (self.host, i, self.retry_time)) try: ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(host_ip) break except paramiko.AuthenticationException: print("Authentication failed when connecting to %s" % host_ip) sys.exit(1) except: print("Could not SSH to %s, waiting for it to start" % host_ip) i += 1 time.sleep(2) # If we could not connect within time limit if i >= self.retry_time: print("Could not connect to %s. Giving up" % host_ip) sys.exit(1) # After connection is successful # Send the command for command in cmd_list: # print command print "> " + command # execute commands stdin, stdout, stderr = ssh.exec_command(command) # TODO() : if an error is thrown, stop further rules and revert back changes # Wait for the command to terminate while not stdout.channel.exit_status_ready(): # Only print data if there is data to read in the channel if stdout.channel.recv_ready(): rl, wl, xl = select.select([ stdout.channel ], [ ], [ ], 0.0) if len(rl) > 0: tmp = stdout.channel.recv(1024) output = tmp.decode() print output # Close SSH connection ssh.close() return def main(args=None): if args is None: print "arguments expected" else: # args = {'<ip_address>', <list_of_commands>} mytest = Commands() mytest.run_cmd(host_ip=args[0], cmd_list=args[1]) return if __name__ == "__main__": main(sys.argv[1:]) 

谢谢!

我用paramiko一堆(很好)和pxssh (也很好)。 我会推荐。 他们的工作有一点不同,但在使用上有相当大的重叠。

我build议使用ssh_decorate

简单如下:

 from ssh_decorate import ssh_connect ssh=ssh_connect('user','password','server') #Run a python function @ssh def python_pwd(): import os return os.getcwd() print (python_pwd()) #Run a bash command ssh>>"ls"