1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
|
import paramiko
import os
class ParamikoHelper():
def __init__(self,remote_ip, remote_ssh_port, private_key_file, ssh_username ):
self.remote_ip = remote_ip
self.remote_ssh_port = remote_ssh_port
self.ssh_username = ssh_username
self.private_key = paramiko.RSAKey.from_private_key_file(private_key_file) # 实例化一个私钥对象
def connect_ssh(self):
try:
self.ssh = paramiko.SSHClient()
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.ssh.connect(hostname=self.remote_ip, port=self.remote_ssh_port, username=self.ssh_username,
pkey=self.private_key)
except Exception as e:
print(e)
return self.ssh
def close_ssh(self):
try:
self.ssh.close()
except Exception as e:
print(e)
def exec_shell(self, shell):
ssh = self.connect_ssh()
try:
stdin, stdout, stderr = ssh.exec_command(shell)
return stdin, stdout, stderr
except Exception as e:
print(e)
def sftp_put_file(self, file, local_dir, remote_dir):
try:
t = paramiko.Transport((self.remote_ip, self.remote_ssh_port))
t.connect(username=self.ssh_username, pkey=self.private_key)
sftp = paramiko.SFTPClient.from_transport(t)
sftp.put(os.path.join(local_dir, file), remote_dir)
t.close()
except Exception:
print("connect error!")
def sftp_get_file(self, file, local_dir, remote_dir):
try:
t = paramiko.Transport((self.remote_ip, self.remote_ssh_port))
t.connect(username=self.ssh_username, pkey=self.private_key)
sftp = paramiko.SFTPClient.from_transport(t)
sftp.get(remote_dir, os.path.join(local_dir, file))
t.close()
except Exception:
print("connect error!")
def main():
remote_ip = '192.168.196.134'
remote_ssh_port = 22
ssh_username = 'root'
private_key_file = 'performance_rsa_4096' # RSA私钥
ph = ParamikoHelper(remote_ip=remote_ip,remote_ssh_port=remote_ssh_port,private_key_file=private_key_file,ssh_username=ssh_username)
# 远程执行ssh命令
shell = "df -h | grep dev"
stdin, stdout, stderr = ph.exec_shell(shell)
for line in stdout.readlines():
print(line)
ph.close_ssh()
# 上传文件file4.txt到远程服务器上
file = 'file4.txt'
remote_dir = '/root/test_log/' + file
local_dir = os.getcwd()
ph.sftp_put_file(file=file, local_dir=local_dir, remote_dir=remote_dir)
# 下载文件file3.txt
file = 'file3.txt'
remote_dir = '/root/test_log/' + file
local_dir = os.getcwd()
ph.sftp_get_file(file=file, local_dir=local_dir, remote_dir=remote_dir)
if __name__ == '__main__':
main()
|