Skip to content

Instantly share code, notes, and snippets.

@Aeternam
Created December 13, 2016 08:44
Show Gist options
  • Save Aeternam/a6d5d512d3fc0b57e952960f42aef2d2 to your computer and use it in GitHub Desktop.
Save Aeternam/a6d5d512d3fc0b57e952960f42aef2d2 to your computer and use it in GitHub Desktop.
# 封装paramiko,实现文件发送
def push_file(ip, local_file, remote_file, port=22, user="root", pkey="/root/.ssh/id_rsa"):
try:
p_key = paramiko.RSAKey.from_private_key_file(pkey)
scp = paramiko.Transport((ip, port))
scp.connect(username=user, pkey=p_key)
sftp = paramiko.SFTPClient.from_transport(scp)
sftp.put(localpath=local_file, remotepath=remote_file)
scp.close()
result = {"status": True, "info": "Push file {0} to {1} succeed.".format(local_file, ip)}
except Exception, e:
result = {"status": False, "info": e}
return result
# 封装paramiko,实现远程命令执行
def remote_exec(ip, cmd, port=22, user="root", pkey="/root/.ssh/id_rsa"):
key = paramiko.RSAKey.from_private_key_file(pkey)
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.load_system_host_keys()
try:
ssh.connect(ip, port, user, key, timeout=300)
stdin, stdout, stderr = ssh.exec_command(cmd)
s_out = stdout.read()
s_err = stderr.read()
if s_err:
result = {"status": False, "info": s_err}
else:
result = {"status": True, "info": s_out}
ssh.close()
except Exception, e:
struc_ret = {"status": False, "info": e[1]}
result = {"status": False, "info": json.dumps(struc_ret)}
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment