1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| import paramiko import os
def connect_remote(): host = '123.123.123.123' port = 22 name = 'abc' password = '123456'
ssh_client = paramiko.SSHClient() ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh_client.connect(hostname=host, port=port, username=name, password=password)
transport = paramiko.Transport((host, port)) transport.connect(username=name, password=password) return ssh_client, transport
if __name__ == '__main__': local_dir = 'E:/markdown/blog/' remote_dir = r'/usr/local/blog/source/_posts/'
print("=== sftp python v0.1 ===") print(" 连接服务器... ") ssh, sftp = connect_remote() print(" 连接成功 ") print(" 1.查看博客路径") print(" 2.上传Post文章") print(" 3.下载Post文章") print(" 4.按q退出")
while 1: answer = input() if answer == 'q': ssh.close() sftp.close() exit(0)
if int(answer) == 1: stdin, stdout, stderr = ssh.exec_command('ls ' + remote_dir) res, err = stdout.read(), stderr.read() result = res if res else err print(result.decode())
elif int(answer) == 2: for basedir, sub_directory, sub_file in os.walk(local_dir): for i in sub_file: print(i) file = input("which file want to upload?\n") sftp_client = paramiko.SFTPClient.from_transport(sftp) print(local_dir + file + '.md', remote_dir + file + '.md') sftp_client.put(local_dir + file + '.md', remote_dir + file + '.md') print("ok!\n")
elif int(answer) == 3: stdin, stdout, stderr = ssh.exec_command('ls ' + remote_dir) res, err = stdout.read(), stderr.read() result = res if res else err print(result.decode())
file = input("which file want to download?\n") sftp_client = paramiko.SFTPClient.from_transport(sftp) sftp_client.get(remote_dir + file + '.md', local_dir + file + '.md') print("ok!\n")
|