我们使用Python如何调用Linux的Shell命令: 如在linux系统下,直接import os 模块即可
下面介绍下如何在windows下使用python远程调用Sehll
1.登录到远程linux服务器需要导入模块
import paramiko
2.定义函数,登录操作系统
def loginLinux(sys_ip,username,password,cmds):
try:
#创建连接client
client=paramiko.SSHClient()
#处理第一次连接Linux的‘yes’ or ‘no’
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#用户名密码连接
client.connect(sys_ip, 22, username=username, password=password, timeout=20)
例如有linux服务器上有log文件如下:
远程执行命令并返回结果:
stdin, stdout, stderr=client.exec_command(cmds)
results = stdout.readlines()
return results
except
Exception, e:
print
e
finally
:
client.close()
if
__name__
=
=
"__main__"
:
sys_ip
=
"192.168.1.110"
username
=
"root"
password
=
"111111"
cmds="sed '1,2d;$d'" + " %s" % txtfile + " | awk '{ sum += $2 ; average = sum/NR} END { printf \"%.2f%\\n\", average }'"
print
ssh(sys_ip,username,password,cmds)