Last active
July 5, 2016 14:13
-
-
Save kurozumi/6ea2ad6ba2e006c43ea54b2eff97030c to your computer and use it in GitHub Desktop.
【Python】リモートサーバーにある複数のファイルの中からひとつのファイルを取得して削除する方法
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from paramiko import SSHClient, AutoAddPolicy | |
from scp import SCPClient | |
def scp_file(): | |
host = "host" | |
port = 22 | |
user = "remote" | |
pswd = "pswd" | |
client = SSHClient() | |
client.set_missing_host_key_policy(AutoAddPolicy()) | |
client.connect(host, port=port, username=user, password=pswd) | |
# リモートのファイル一覧を標準出力する | |
stdin, stdout, stderr = client.exec_command("cd /home/remote/dir && ls") | |
# 標準出力したリストを改行で分割してファイルリストを作成 | |
files = stdout.read().strip("\n").split("\n") | |
# spcでリモートのファイルの一つをローカルにコピー | |
with SCPClient(client.get_transport()) as scp: | |
scp.get("/home/remote/%s" % files[0], "/home/local/") | |
# リモートのファイルを削除 | |
client.exec_command("rm /home/remote/%s" %s files[0]) | |
# 終了 | |
client.close() | |
if __name__ == "__main__": | |
scp_file() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment