程式扎記: [ Python 常見問題 ] How do I copy a file to a remote server in python using scp or ssh?

標籤

2014年7月1日 星期二

[ Python 常見問題 ] How do I copy a file to a remote server in python using scp or ssh?

來源自 這裡
Question:
As title.

Solution:
方法一:
If you want the simple approach, this should work. You'll want to ".close()" the file first so you know it's flushed to disk from Python. Also you will need to generate (on the source machine) and install (on the destination machine) an ssh key beforehand so that the scp automatically gets authenticated with your public ssh key (in other words, so your script doesn't ask for a password). Below is the sample code to comply with your request:
  1. import os  
  2. os.system("scp FILE USER@SERVER:PATH")  
  3. #e.g. os.system("scp foo.bar joe@srvr.net:/path/to/foo.bar")  
References:
[Linux 小學堂] SSH 免密碼登入
鳥哥的 Linux - 檔案異地直接複製: scp
Python module - os: os.system(command)
Execute the command (a string) in a subshell. This is implemented by calling the Standard C function system(), and has the same limitations.

方法二:
To do this in Python (i.e. not wrapping scp through subprocess.Popen or similar) with the Paramiko library, you would do something like this:
  1. import os  
  2. import paramiko  
  3.   
  4. ssh = paramiko.SSHClient()   
  5. ssh.load_host_keys(os.path.expanduser(os.path.join("~"".ssh""known_hosts")))  
  6. ssh.connect(server, username=username, password=password)  
  7. sftp = ssh.open_sftp()  
  8. sftp.put(localpath, remotepath)  
  9. sftp.close()  
  10. ssh.close()  
If you want to execute command in remote server, below is the sample code:
  1. ssh = paramiko.SSHClient()  
  2. ssh.connect(server, username=username, password=password)  
  3. ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(cmd_to_execute)  


沒有留言:

張貼留言

網誌存檔

關於我自己

我的相片
Where there is a will, there is a way!