通过paramiko实现ssh

简单的ssh小实例

import paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname='10.10.10.143',port=22,username='msfadmin',passward='12345')
while True:
    cmd = input('>>>')
    stdin, stdout, stderr = ssh.exec_command(cmd)
    if stdout:
        result = stdout.read()
        
    else:
        result = stderr.read()
    print(result.decode())

ssh.close()

一个scp的小实例

import paramiko

transport = paramiko.Transport(('10.10.10.143',22))
transport.connect(username='msfadmin',password='msfadmin')
sftp = paramiko.SFTPClient.from_transport(transport)

# localpath = input('>>>')
# print(localpath)
# sftp.put('test.py', '/tmp/a')

sftp.get('/tmp/id_rsa', 'b.txt')

transport.close()

通过ssh-keygen命令

ssh-keygen

也可直接使用命令将公钥传到目标机器

ssh-copy-id '-p 端口 [email protected]'

通过密钥链接linux

import paramiko

private_key = paramiko.RSAKey.from_private_key_file('b.txt')
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname='10.10.10.143',port=22,username='msfadmin',pkey=private_key)
while True:
    cmd = input('>>>')
    stdin, stdout, stderr = ssh.exec_command(cmd)
    if stdout:
        result = stdout.read()
        
    else:
        result = stderr.read()
    print(result.decode())

ssh.close()

你可能感兴趣的:(通过paramiko实现ssh)