Pythonにおけるparamikoモジュールの使用
2907 ワード
paramikoはSSHプロトコルをサポートし、LinuxやWindows(SSHサービスを構築した)と対話することができ、リモートでコマンドを実行したり、ファイルのアップロード/ダウンロードなどの操作を実行したりすることができます.
コードは次のとおりです.
コードは次のとおりです.
import os
import paramiko
def exec_command(ip, port, username, password, cmd):
"""
"""
paramiko.util.log_to_file("paramiko.log")
ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=ip, port=int(
port), username=username, password=password, timeout=5)
stdin, stdout, stderr = ssh.exec_command('cmd.exe /C "%s"' % cmd)
ssh.close()
def upload_file(ip, port, username, password, local_file_path, remote_file_path):
"""
"""
paramiko.util.log_to_file("paramiko.log")
trans = paramiko.Transport((ip, int(port)))
trans.connect(username=username, password=password)
sftp = paramiko.SFTPClient.from_transport(trans)
sftp.put(local_file_path, remote_file_path)
trans.close()
def download_file(ip, port, username, password, local_file_path, remote_file_path):
"""
"""
paramiko.util.log_to_file("paramiko.log")
trans = paramiko.Transport((ip, int(port)))
trans.connect(username=username, password=password)
sftp = paramiko.SFTPClient.from_transport(trans)
sftp.get(remote_file_path, local_file_path)
trans.close()
def upload_dir(ip, port, username, password, local_dir, remote_dir):
""" ( windows )
"""
paramiko.util.log_to_file("paramiko.log")
trans = paramiko.Transport((ip, int(port)))
trans.connect(username=username, password=password)
sftp = paramiko.SFTPClient.from_transport(trans)
try:
sftp.mkdir(remote_dir)
except Exception, e:
pass
for root, dirs, files in os.walk(local_dir):
for file_name in files:
local_file_path = os.path.join(root, file_name)
remote_file_path = os.path.join(
remote_dir, local_file_path[3:]) # :windows
remote_file_path = remote_file_path.replace("\\", "/")
try:
sftp.put(local_file_path, remote_file_path)
except Exception, e:
sftp.mkdir(os.path.dirname(remote_file_path))
sftp.put(local_file_path, remote_file_path)
for dir_name in dirs:
local_dir = os.path.join(root, dir_name)
remote_path = os.path.join(remote_dir, local_dir[3:])
remote_path = remote_path.replace("\\", "/")
try:
sftp.mkdir(os.path.dirname(remote_path))
sftp.mkdir(remote_path)
except Exception, e:
pass
trans.close()