我正在尝试将一些文件夹复制到在Linux上运行的远程计算机上。下面是我使用的代码,我不确定需要添加什么才能使副本发生
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(
paramiko.AutoAddPolicy())
ssh.connect('xxx.xxx.xx.xx', username='root',
password='xxxxxxx')
#scp -r /mnt/hgfs/windows-D-drive/Testing/ root@xxx.xxx.xx.xx:/home # equivalent code here
答案 0 :(得分:1)
这里最简单的方法是压缩文件并使用sftp.put将文件放在远程计算机上并通过远程计算机提取它:
tar = tarfile.open("Tests.tar.gz", "w:gz")
path_me = os.path.dirname(os.path.realpath(sys.argv[0]))
tar.add(path_me, arcname="Tests")
tar.close()
transport = paramiko.Transport((SERVER_IP, 22))
transport.connect(username = 'root', password = 'xxxxx')
sftp = paramiko.SFTPClient.from_transport(transport)
remotepath='/home/Tests.tar.gz'
localpath=os.path.join(path_me+"/Tests.tar.gz")
#print(localpath)
sftp.put(localpath, remotepath)
sftp.close()
transport.close()
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(SERVER_IP, username='root', password='philips')
stdin, stdout, stderr = ssh.exec_command("tar -C /home -xzf /home/Tests.tar.gz")
答案 1 :(得分:0)
import paramiko
import os
client=paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
with open ("/home/vikas/Desktop/password.txt" ) as a:
ip,username,password=a.readline().split(" ")
client.connect(hostname=ip,username=username ,password=password)
sftp_client=client.open_sftp()
#client.exec_command("cd")
# LETS make 'aaaa' folder sync with server
#/root/ is home for remote server
localfolder="/home/vikas/Desktop/aaaa/"
basefolder="/".join(localfolder.split("/")[:-2])
for path,dirs,files in os.walk(localfolder):
if path.lstrip(localfolder)!=None:
extrapath=path.split(basefolder)[-1]
command="mkdir /root/{}".format(extrapath)
client.exec_command(command)
for file in files:
filepath=os.path.join(path,file)
extrapath=path.split(basefolder)[-1]
sftp_client.put(filepath,"/root/{}/{}".format(extrapath,file))
sftp_client.close()
client.close()