python远程执行命令
python远程ssh
1. python远程执行命令
#!/usr/bin/python
# -*- coding: utf-8 -*-
import paramiko
# from cryptography.hazmat.backends import default_backend
import time
def excuseRemoteCmd(ipaddr, port, username, pwd, cmd):
print(ipaddr, port, username, pwd, cmd)
try:
# 创建SSH对象
ssh = paramiko.SSHClient()
# 允许连接不在know_hosts文件中的主机
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
ssh.connect(ipaddr, port=port, username=username,
password=pwd, timeout=10)
# 打开一个Channel并执行命令
# stdout 为正确输出,stderr为错误输出,同时是有1个变量有值
stdin, stdout, stderr = ssh.exec_command(cmd, get_pty=True, timeout=60)
# 打印执行结果
# for item in stdout.readlines():
# print item
while not stdout.channel.exit_status_ready():
result = stdout.readline()
print(result)
if stdout.channel.exit_status_ready():
result = stdout.readlines()
print(result)
break
# 错误打印
err_list = stderr.readlines()
if len(err_list) > 0:
print 'ERROR:' + err_list
# exit()
# 关闭连接
ssh.close()
return stdout, stderr
except Exception as e:
print(e)
return stdout, stderr
2. shell远程执行命令
# 远程执行脚本
CardCmd = "ssh -T -o ServerAliveInterval=5 -p %s %s@%s \"sh /opt/xxx/sed_network_card.sh %s\"" % (
remotePort, username, remoteIp, remoteIp)
print("getNetCardCmd:%s" % (CardCmd))
status, output = commands.getstatusoutput(CardCmd)
if status != 0:
print("cmd result:%s,status:%s" % (output, status))
return status, output
----------------------------------------------------------------------------
# 远程拷贝
Cmd = "scp " + " -P " + remotePort + " " + SrcPath + \
" "+username+"@"+remoteIp+":" + DstPath
print("Cmd:", Cmd)
status, output = commands.getstatusoutput(Cmd)
if status != 0:
print("cmd result:%s,status:%s" % (output, status))
return status, output
【励志篇】:
古之成大事掌大学问者,不惟有超世之才,亦必有坚韧不拔之志。