Python run command on romote linux

自动化需要,要远程执行Linux命令,使用了Paramiko

安装

非常简单

1
pip install paramiko

使用

1
2
3
4
5
6
7
8
9
10
11
12
import paramiko

def ssh_exec(hostname, port, username, password, execmd):

s = paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())

s.connect(hostname=hostname, port=port, username=username, password=password)
stdin, stdout, stderr = s.exec_command(execmd)
stdin.write("Y") # Generally speaking, the first connection, need a simple interaction.

s.close()

调用

1
2
3
4
5
6
7
8
if __name__ == "__main__":
hostname = 'xxx.com'
port = 22
username = 'xxx'
password = 'xxx'
execmd = "cd /home/qa/" # 执行多条命令用分号分隔

ssh_exec(hostname, port, username, password, execmd)

唐胡璐 wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!
分享创造价值,您的支持将鼓励我继续前行!