安装
pip install paramiko
基于用户名密码的连接
import paramiko
ssh = paramiko.SSHClient()
# 允许连接不在 know_hosts 文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(<host>, 22, <username>, <password>)
stdin, stdout, stderr = ssh.exec_command('hostname')
for line in stdout:
print(line.replace('\n', ''))
for line in stderr:
print(line.replace('\n', ''))
stdin, stdout, stderr = ssh.exec_command('id')
for line in stdout:
print(line.replace('\n', ''))
for line in stderr:
print(line.replace('\n', ''))
ssh.close()
基于公钥密钥的连接
import paramiko
private_key = paramiko.RSAKey.from_private_key_file('/home/kongxx/.ssh/id_rsa')
ssh = paramiko.SSHClient()
# 允许连接不在 know_hosts 文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=<host>, port=22, username=<username>, pkey=private_key)
stdin, stdout, stderr = ssh.exec_command('hostname')
for line in stdout:
print(line.replace('\n', ''))
for line in stderr:
print(line.replace('\n', ''))
stdin, stdout, stderr = ssh.exec_command('id')
for line in stdout:
print(line.replace('\n', ''))
for line in stderr:
print(line.replace('\n', ''))
ssh.close()
网友评论