Python:如何通过SSH和paramiko复制文件而不使用sftp

时间:2015-12-15 12:42:48

标签: python ssh sftp paramiko

我想使用paramiko库在python(3.4)中复制一个文件。

我的方法:

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(192.168.1.1, 22, root, root)
sftp = ssh.open_sftp()
sftp.put(local_file, remote_file)
sftp.close()

我得到的错误:

EOF during negotiation

问题是连接的系统没有使用sftp。

那么有没有办法在不使用sftp的情况下复制文件?

2 个答案:

答案 0 :(得分:1)

您可以使用scp发送文件,sshpass可以使用密码。

import os

os.system('sshpass  -p "password" scp local_file root@192.168.1.?:/remotepath/remote_file')

答案 1 :(得分:1)

Use the built in paramiko.Transport图层中创建所有元素并创建自己的Channel

with paramiko.SSHClient() as ssh:
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect('192.168.1.1', 22, 'root', 'root')

    transport = ssh.get_transport()
    with transport.open_channel(kind='session') as channel:
        file_data = open('local_data', 'rb').read()
        channel.exec_command('cat > remote_file')
        channel.sendall(file_data)