paramiko遠程上傳下載文件


import paramiko
import sys


user = "root"
pwd = "123456"



# 上傳文件
def sftp_upload_file(server_path, local_path):
    try:
        t = paramiko.Transport((ip, 22))
        t.connect(username=user, password=pwd)
        sftp = paramiko.SFTPClient.from_transport(t)
        sftp.put(local_path, server_path)
        t.close()
    except Exception as  e:
        print(e)

# 下載文件
def sftp_down_file(server_path, local_path):
    try:
        t = paramiko.Transport((ip, 22))
        t.connect(username=user, password=pwd)
        sftp = paramiko.SFTPClient.from_transport(t)
        sftp.get(server_path, local_path)
        t.close()
    except Exception as e:
        print(e)

# 連接
def ssh_conn(ip, cmd):

    ssh = paramiko.SSHClient()
    # 允許連接不在known_hosts文件上的主機
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    # 連接服務器
    ssh.connect(ip, 22, user, pwd)
    # 執行命令
    stdin, stdout, stderr = ssh.exec_command(cmd)
    # 獲取結果
    print(10 * "-", 'start', 10 * "-")
    for line in stdout:
        res=(line.strip('\n').split())
        print(res)
    else:
        print(stdout)
    print(10 * "-", 'end', 10 * "-")

def menu():
    print('''
    * - - - - - - - - - - - - - - - - - *     
                   菜單                     
                1>上傳文件                 
                2>下載文件
                3>執行命令
                4>退出
    * - - - - - - - - - - - - - - - - - *
    ''')

    choice = int(input('請輸入你要執行的操作:\n'))
    if choice == 1:
        src = input('請輸入原路徑:\n')
        dest = input('請輸入目標路徑:\n')
        sftp_upload_file(src, dest)
    elif choice == 2:
        src = input('請輸入原路徑:\n')
        dest = input('請輸入目標路徑:\n')
        sftp_down_file(src, dest)
    elif choice == 3:
        while True:
            cmd = input('請輸入要執行的命令:\n')
            if cmd == 'eixt':
                sys.exit()
            ssh_conn(ip, cmd)
    else:
        sys.exit()


if __name__ == '__main__':
    ip = input('請輸入目標ip:\n')
    while True:
        menu()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM