问题:
paramiko模块上传文件失败,提示paramiko.ssh_exception.SSHException: Channel closed.
使用python3 paramiko库实现向远程服务器上传文件,脚本如下:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import paramiko
import uuid
import os
class Haproxy(object):
def __init__(self):
self.host = '10.224.96.87'
self.port = 22
self.username = 'root'
self.pwd = 'tahoe.webex'
self.__k = None
def create_file(self):
file_name = str(uuid.uuid4())
with open(file_name,'w') as f:
f.write('sb')
return file_name
def run(self):
self.connect()
self.upload()
# self.rename()
#self.close()
def connect(self):
transport = paramiko.Transport((self.host,self.port))
transport.connect(username=self.username,password=self.pwd)
self.__transport = transport
print("Connected to %s as %s" % (self.host, self.username))
def close(self):
self.__transport.close()
def upload(self):
# 连接,上传
#file_name = self.create_file()
localpath= r'C:\PF\cpu_memory.py'
remotepath = r'/home/test.py'
sftp = paramiko.SFTPClient.from_transport(self.__transport)
# 将location.py 上传至服务器 /tmp/test.py
sftp.put(localpath, remotepath)
print("File %s has uploaded to %s" % (localpath, remotepath))
def rename(self):
ssh = paramiko.SSHClient()
ssh._transport = self.__transport
# 执行命令
stdin, stdout, stderr = ssh.exec_command('mv /home/root/tttttttttttt.py /home/root/ooooooooo.py')
# 获取命令结果
result = stdout.read()
ha = Haproxy()
ha.run()
但运行时报错如下:
但运行时报错如下:
C:\Users\yunliu3\AppData\Local\Programs\Python\Python39\python.exe C:/PF/test_bak.py
Connected to 10.224.96.87 as root
Traceback (most recent call last):
File "C:\PF\test_bak.py", line 77, in <module>
ha.run()
File "C:\PF\test_bak.py", line 43, in run
self.upload()
File "C:\PF\test_bak.py", line 62, in upload
sftp = paramiko.SFTPClient.from_transport(self.__transport)
File "C:\Users\yunliu3\AppData\Local\Programs\Python\Python39\lib\site-packages\paramiko\sftp_client.py", line 169, in from_transport
chan.invoke_subsystem("sftp")
File "C:\Users\yunliu3\AppData\Local\Programs\Python\Python39\lib\site-packages\paramiko\channel.py", line 72, in _check
return func(self, *args, **kwds)
File "C:\Users\yunliu3\AppData\Local\Programs\Python\Python39\lib\site-packages\paramiko\channel.py", line 283, in invoke_subsystem
self._wait_for_event()
File "C:\Users\yunliu3\AppData\Local\Programs\Python\Python39\lib\site-packages\paramiko\channel.py", line 1226, in _wait_for_event
raise e
paramiko.ssh_exception.SSHException: Channel closed.
Process finished with exit code 1
原因:因为服务器sftp的服务未开启
解决:
1.打开/etc/ssh/sshd_config
2.加入下面的代码(首先查询一下sftp-server的路径
[root@frdsa002 ~]# find / -name sftp-server
/usr/libexec/openssh/sftp-server)
Subsystem sftp
/usr/libexec/openssh/sftp-server

