需要额外安装
pip3 install paramiko
SSH远程机器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| import paramiko
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname='192.168.10.102',username='root',password='1')
stdin,stdout,stderr=ssh.exec_command('lsblk') print("标准输出:\n",stdout.read().decode('utf-8'))
ssh.close()
|
SFTP传输文件
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
| import paramiko,os
ssh=paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
hostname='192.168.10.102' username='root' password='1'
local_dir='/usr/local/' local_file='test.txt' local_path=os.path.join(local_dir,local_file) remote_path='/tmp/test.txt'
try: ssh.connect(hostname=hostname, username=username, password=password) print('ssh连接成功') sftp=ssh.open_sftp() os.makedirs(local_dir, exist_ok=True) print(f'已确保本地目录存在: {local_dir}')
with open(local_path, 'w') as f: f.write('这是测试文件的内容。') print(f'已创建并写入本地文件: {local_path}')
sftp.put(local_path,remote_path) print(f"成功上传文件:{local_path}到{hostname}:{remote_path}")
except Exception as e: print(f"错误{e}")
finally: sftp.close() ssh.close()
|