一言

loading...

0%

paramiko

paramiko的使用

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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# encoding: utf-8

"""
@author: Henry
@site:
@software: PyCharm
@file: transfer.py
@time: 2019/11/3 20:00
"""

import os
import paramiko
from paramiko.ssh_exception import NoValidConnectionsError, AuthenticationException, SSHException

class SshRemoteHost(object):
def __init__(self, hostname, port, user, passwd):
self.hostname = hostname
self.port = port
self.user = user
self.passwd = passwd

def do_cmd(self, cmd):
client = paramiko.SSHClient()

client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

try:

client.connect(hostname=self.hostname,
port=self.port,
username=self.user,
password=self.passwd)

print("正在连接%s......." % (self.hostname))
except NoValidConnectionsError as e:
print("连接失败:", e)
except AuthenticationException as e:
print("密码错误")
else:
# 4. 执行操作
stdin, stdout, stderr = client.exec_command(cmd)

# 5.获取命令执行的结果
result = stdout.read().decode('utf-8')
print(result)
finally:
# 6.关闭连接
client.close()

def do_put(self, localdir=None, remotedir=None):
"""
上传文件
:return:
"""
if not localdir:
localdir = os.getcwd()
print('正在上传...')
# 获取Transport实例
tran = paramiko.Transport(self.hostname, int(self.port))
try:
# 连接SSH服务端
tran.connect(username=self.user, password=self.passwd)
except SSHException as e:
print('连接失败:', e)
else:
# 获取SFTP实例
sftp = paramiko.SFTPClient.from_transport(tran)
files = os.listdir(localdir)
print(files)
files = ['t1.txt', 't2.txt']
print(files)
for f in files:
print('####################################################')
print('Begin to upload file to %s ' % self.hostname)
print('Uploading ', os.path.join(localdir, f))
sftp.put(os.path.join(localdir, f), os.path.join(remotedir, f))
print('Upload Success ', os.path.join(localdir, f))
else:
print('上传文件信息错误')
finally:
tran.close()

def do_get(self, remotedir, localdir=None):
if not localdir:
localdir = os.getcwd()
print('正在下载...')
# 获取Transport实例
tran = paramiko.Transport(self.hostname, int(self.port))
try:
# 连接SSH服务端
tran.connect(username=self.user, password=self.passwd)
except SSHException as e:
print('连接失败: ', e)
else:
# 获取SFTP实例
sftp = paramiko.SFTPClient.from_transport(tran)
try:

remote_files = sftp.listdir(remotedir)
for f in remote_files: # 遍历读取远程目录里的所有文件
sftp.get(os.path.join(remotedir, f), os.path.join(localdir, f))
except IOError: # 如果目录不存在则抛出异常
return ("remote_path or local_path is not exist")
finally:
tran.close()

if __name__ == '__main__':
"""
1.上传文件到服务器
2.复制服务器文件到指定目录
3.运行python脚本
4.下载文件到本地
"""
hostname = '****'
port = '22'
user = '**'
passwd = '****'
cmd = 'cd /home/student/test;pwd;cp test.py ../test_2'
localdir = ''
remotedir1 = '~/student/test'
remotedir2 = '~/student/test_2'
client = SshRemoteHost(hostname, port, user, passwd)

# client.do_put(localdir, remotedir1)

client.do_cmd(cmd)
client.do_get(remotedir2, localdir)

坚持原创技术分享,您的支持将鼓励我继续创作!