在python语言中实现远程服务器执行命令+远程dcoker执行命令

 1 def ssh_exec_command(ip, username, password, cmd=None):
 2     """
 3     ssh执行命令
 4     :param ip:  IP address for target machine
 5     :param username:
 6     :param password:
 7     :param cmd:  Prepare for execute commands on target machine
 8     :return:
 9     """
10     try:
11         ssh = paramiko.SSHClient()
12         # add host_allow
13         ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
14         # use secret-key login remote machines
15         # private_keys = paramiko.RSAKey.from_private_key_file(pkey_path)
16 
17         ssh.connect(hostname=str(ip), port=22, username=username, password=password)
18 
19         stdin, stdout, stderr = ssh.exec_command(cmd)
20 
21         stdout_result = stdout.readlines()
22         stderr_result = stderr.readlines()
23 
24         if stderr_result:
25             return False
26         else:
27             return stdout_result
28 
29     except Exception as e:
30         print(str(e))
31         return False
32     finally:
33         ssh.close()

 

备注:如果想在一条命令里执行多个指令,可以将多个指令使用“;”分割。