΢ Ͷ ^ ھ

cba季后赛赛程 :Python paramiko ?dzMSSHҪģM

cba㶫 www.axwwg.com  •rg2020-03-03 13:14:36   ߣ   ҪuՓ(0)

߀]YСֻլڼҲȥͻloҷһƪ̳PPython paramiko ?dzMSSHҪģM
Ҷ֪ͨ^SSHտ

߀]YСֻլڼҲȥͻloҷһƪ̳PPython paramiko ?dzMSSHҪģM

Ҷ֪ͨ^SSHտhBӵLinux鿴־Bh̷ļςļdPythonparamiko?ͬʵK߀?

҂Ҫb@һ??pycharmh²

һbparamiko??/span>

PyCharmPreferencesProjectĿProject Interpreter

c^ָ̖ݔxb

ɺProject Interpreter@ʾψD

 Ñܴa sshclient ʽ

import paramiko
# SSH
ssh = paramiko.SSHClient()
# SBӲknow_hostsļеC
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# Bӷ
ssh.connect(hostname='192.168.199.146', port=22, username='fishman', password='9')
# 
stdin, stdout, stderr = ssh.exec_command('df')
# @ȡY
res,err = stdout.read(),stderr.read()
result = res if res else err
print(result.decode())
# P]B
ssh.close()

Ȍ??Ȼ󄓽һSSHȻͨ^Bh̙CĬJ˿22@Bӵ192.168.199.146ęCܴa9Ȼdf@ȡصĽY

҂Ա^һͨ^SSHõĽY

Ñܴa transport ʽ

SSHClientǂyBӷP]һЕrҪϷжς/dļ淽toFͨ^·ʽ

#SSHClient b Transport
import paramiko
# һtransport
transport = paramiko.Transport(('192.168.199.146', 22))
# B
transport.connect(username='fishman', password='9')
# sshclientČtransportָϵtransport
ssh = paramiko.SSHClient()
ssh._transport = transport
# ͂yһ
stdin, stdout, stderr = ssh.exec_command('df')
print (stdout.read().decode())
# P]B
transport.close()

ڹB

4.1 SSHܵ

҂֪ͨ^ùԌFSSHܵFBfishmanCʾ҂ݔܴaȻܵ

ͨ^SSHԭc\нB҂֪ҪFܹ耵Ҫ҂ԼCĹ耴惦ҪꑵhC䛵ĕrhCÑlһSCַÑԼ˽耼ٰܺl؁hCȃĹMнɹCÑǿŵֱSshellҪܴa

҂ԼĹͨ^ ssh-keygen@ʾ@耱ļ·ĬJȻ܇@ұѽɵĹʾǷҪw@Ͳ،؛]^^m܇ʾҪҪ˽Oÿpassphrase˽耵İȫ@OһĬJҲֱӻ܇

õ耺һNͨ^ֱӂh̙Cssh-copy-id [email protected]҂ꑵęC:

ssh-copy-id [email protected]

һNM빫ļȥ,M.ssh/id_rsa.pubͨ^morecatƹ

~ more .ssh/id_rsa.pub ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCyQ2GtkbKcFAP/kX/+65e91Q8EJ+twpyqjEBzlVmZ2mxy8Zw7b/AfeV60ehloCq7p521IGJaXWbr3bky7Jljc6x7cAZsRW7mZRPFelPYa5iJ4lIshU3RwhbTYW6RyrG+InF3ognJ7bggpPmJbWFxqqpZwdkEilpnv0+8b17frSbF1xaQQh57vDjG78xr0pys2MBzylqrs1RNiTcRz86zJT7SbujYY/bpiUB78w46CmRlwzHOk8Zg0hcegqSMHjboQyhkSX0xcFv2ZLHm5Gpfba3863M+62Q1r2U+QW5Ki1f3nsGwHWQIRuHNWldUzWKYRPsKJHVvwFwkYDG3sZZMWR [email protected] ~ cat .ssh/id_rsa.pub ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCyQ2GtkbKcFAP/kX/+65e91Q8EJ+twpyqjEBzlVmZ2mxy8Zw7b/AfeV60ehloCq7p521IGJaXWbr3bky7Jljc6x7cAZsRW7mZRPFelPYa5iJ4lIshU3RwhbTYW6RyrG+InF3ognJ7bggpPmJbWFxqqpZwdkEilpnv0+8b17frSbF1xaQQh57vDjG78xr0pys2MBzylqrs1RNiTcRz86zJT7SbujYY/bpiUB78w46CmRlwzHOk8Zg0hcegqSMHjboQyhkSX0xcFv2ZLHm5Gpfba3863M+62Q1r2U+QW5Ki1f3nsGwHWQIRuHNWldUzWKYRPsKJHVvwFwkYDG3sZZMWR [email protected] ~

ƺ҂h̙C,Ŀ.sshļAаlFļid_ras id_ras.pubԓCĹ˽

know_hostssshÿL^ӋCĹ(public key)ӛ~/.ssh/known_hosts´LͬӋCrOpenSSHˌ耲ͬOpenSSHl ܵDNS Hijack֮Ĺ

҂ҪŏƵҵĹ耱浽authorized_keysļ

ͨ^vi_݋ȻճN˳

˕r҂˳ȻµlFͲҪݔܴaԌFܵ

҂Ҫע.sshĿ䛵ęޞ700ļauthorized_keys˽耵ęޞ600tކ}Ÿoܴa

耿ؐ~/.ssh/authorized_keysļзŽ׷N

1ͨ^scpؐȻ׷ӵ~/.ssh/authorized_keysļ@Nʽ^韩scp -P 22 ~/.ssh/id_rsa.pub [email protected]:~/

2ͨ^ssh-copy-idҲǵһNssh-copy-id "-p22 [email protected]",Еr[email protected]Ҫ̖ǰ挑-p˿̖

3ͨ^cat ~/.ssh/id_rsa.pub | ssh -p 22 [email protected] cat >> ~/.ssh/authorized_keys'@ҲDZ^õķԸĶ˿̖

4.2 ڹ耵 SSHClient ʽ

M·鿴ұid_rsaļ·

import paramiko
private_key = paramiko.RSAKey.from_private_key_file('/Users/ljf/.ssh/id_rsa')
# SSH
ssh = paramiko.SSHClient()
# SBӲknow_hostsļеC
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# Bӷ
ssh.connect(hostname='192.168.199.146', port=22, username='fishman', pkey=private_key)
# 
stdin, stdout, stderr = ssh.exec_command('df')
# @ȡY
res,err = stdout.read(),stderr.read()
result = res if res else err
print(result.decode())
# P]B
ssh.close()

ͬ?stransportb

import paramiko
private_key = paramiko.RSAKey.from_private_key_file('/Users/ljf/.ssh/id_rsa')
# һtransport
transport = paramiko.Transport(('192.168.199.146', 22))
# B
transport.connect(username='fishman', pkey=private_key)
ssh = paramiko.SSHClient()
ssh._transport = transport
stdin, stdout, stderr = ssh.exec_command('df')
# @ȡY
res,err = stdout.read(),stderr.read()
result = res if res else err
print(result.decode())
# P]B
ssh.close()

ֱͬӸ˽ַBڱث@ȡ˽ַ

➜ .ssh cat id_rsa -----BEGIN RSA PRIVATE KEY----- MIIEowIBAAKCA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IYCuM2pPKDLpuoSzToqL2YBycokBqZc80ib1rc3a67WL5OxarRpmWaXZL7BJaa +G2mHOHDqZgv00tnj/gUcAB3Yuqps9y+OPtHnGwUphoNW+nk/wjcHLsj+6I2BKnB gZeKvzUBvdcdTh13yUEknQKBgHBkmNEbPP/+IXutwdrCLYQnyXq30Mdwqzz/ZxQz BHABK9RUeCHlkCj2X/qBJsBQudxz5ABxBbTH5gC3gvDKrMhcYT5EGSKP9rcIt09H /faKP+eS8TFp882CMCOcxwS25b+L8ZcLTIHyvOOeIrweZ/qFlsbY+UjwUmNFzcfk rmPdAoGBAJ9NWhf16aLQxUrPkUvHK9k7ONUadamBxA6NNvHMZxow81/p9VQK71o7 iUdJmC/+VOvGqbA3AbtqkbjBMUWGjEeVKLxMnCZngfu9J6bnWDUaYbQz3gVY63ca KFWjRXO6GtynW0Dec0Nj/q22V5J+2ZCkIvSAQ+cI04d0Ij7RdKPl -----END RSA PRIVATE KEY----- ➜ .ssh

#!/usr/bin/env python # -*- coding: utf-8 -*- # ˽ַMB import paramiko from io import StringIO key_str = """-----BEGIN RSA PRIVATE KEY----- MIIEowIBAAKCAQEAskNhrZGynBQD/5F//uuXvdUPBCfrcKcqoxAc5VZmdpscvGcO 2/wH3letHoZaAqu6edtSBiWl1m6925MuyZY3Ose3AGbEVu5mUTxXpT2GuYieJSLI VN0cIW02FukcqxviJxd6IJye24IKT5iW1hcaqqWcHZBIpaZ79PvG9e360mxdcWkE Iee7w4xu/Ma9KcrNjAc8paq7NUTYk3Ec/OsyU+0m7o2GP26YlAe/MOOgpkZcMxzp PGYNIXHoKkjB426EMoZEl9MXBb9mSx5uRqX22t/OtzPutkNa9lPkFuSotX957BsB 1kCEbhzVpXVM1imET7CiR1b8BcJGAxt7GWTFkQIDAQABAoIBAH54j7Q0yiMxkCSh dc3GF8H2htDMAZ3K+9T0eYu74LYFFj4UX9Zy2KJGUex2JSX/8CzEDU2PKDkaGFjP 80HR8R0i1BLU1jdWrAC2bvgszoiTB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Dec0Nj/q22V5J+2ZCkIvSAQ+cI04d0Ij7RdKPl -----END RSA PRIVATE KEY-----""" private_key = paramiko.RSAKey(file_obj=StringIO(key_str)) transport = paramiko.Transport(('192.168.199.146', 22)) transport.connect(username='fishman', pkey=private_key) ssh = paramiko.SSHClient() ssh._transport = transport stdin, stdout, stderr = ssh.exec_command('df') res,err = stdout.read(),stderr.read() result = res if res else err print(result.decode()) # P]B ssh.close()

ϵõĽYͬ

@ҪעLinuxOSXϵyôԎSSHϲ]}Windowsôͨ^XsheelҲһ,ͨ^Xsheel----½Ñ

]bXsheelԌLinuxĹcopy^@@xȡشĹϢ

ͨ^sz ~/.ssh/id_rsa耱һtxtļparamiko.RSAKey.from_private_key_file(ļ)

SFTPClientBh̷ςd

҂ӋLocalFile.txtςfishmanCtest·remote.txt@ԓ·ԭļ,remote.txt]Ѓͨ^sftp.put('LocalFile.txt', '/home/fishman/test/remote.txt')ς

Ñܴaςd

import paramiko
# һtrans# һtransport
transport = paramiko.Transport(('192.168.199.146', 22))
# B
transport.connect(username='fishman', password='9')
# һ sftp,ָBӵͨ
sftp = paramiko.SFTPClient.from_transport(transport)
 
# LocalFile.txt ς /home/fishman/test/remote.txt
# sftp.put('LocalFile.txt', '/home/fishman/test/remote.txt')
# LinuxFile.txt d fromlinux.txtļ
sftp.get('/home/fishman/test/LinuxFile.txt', 'fromlinux.txt')
transport.close()

ͬ҂dh̙Ctest·µLinuxFile.txtļfromLinux.txt

ڹςd

import paramiko
private_key = paramiko.RSAKey.from_private_key_file('/Users/ljf/.ssh/id_rsa')
transport = paramiko.Transport(('192.168.199.146', 22))
transport.connect(username='fishman', password='9')
sftp = paramiko.SFTPClient.from_transport(transport)
 
# LocalFile.txt ς /home/fishman/test/remote.txt
# sftp.put('LocalFile.txt', '/home/fishman/test/remote.txt')
# LinuxFile.txt d fromlinux.txtļ
sftp.get('/home/fishman/test/LinuxFile.txt', 'fromlinux.txt')
 
transport.close()

5 FݔRؽYĹ ϲǻB҂댍FһxshellߵĹԺݔ܇ͷؽY

import paramiko
import os
import select
import sys
 
# һsocket
trans = paramiko.Transport(('192.168.2.129', 22))
# һ͑
trans.start_client()
 
# ʹrsa耵䛵Ԓ
'''
default_key_file = os.path.join(os.environ['HOME'], '.ssh', 'id_rsa')
prikey = paramiko.RSAKey.from_private_key_file(default_key_file)
trans.auth_publickey(username='super', key=prikey)
'''
# ʹÑܴa
trans.auth_password(username='super', password='super')
# _һͨ
channel = trans.open_session()
# @ȡK
channel.get_pty()
# K@ӾͿԵ䛵Kͺ҂xshellϵyһ
channel.invoke_shell()
# ͿԈеIJselectF
# ݔKsys.stdin ͨMбO,
# ÑڽKݔochannelͨ@rsys.stdinͰl׃selectͿԸ֪
# channelİl@ȡY^䌍һsocketİlͺͽϢ^
while True:
 readlist, writelist, errlist = select.select([channel, sys.stdin,], [], [])
 # Ñݔ,sys.stdinl׃
 if sys.stdin in readlist:
 # @ȡݔă
 input_cmd = sys.stdin.read(1)
 # lͽo
 channel.sendall(input_cmd)
 
 # ˽Y,channelͨܵY,l׃ select֪
 if channel in readlist:
 # @ȡY
 result = channel.recv(1024)
 # _BӺ˳
 if len(result) == 0:
  print("\r\n**** EOF **** \r\n")
  break
 # ݔĻ
 sys.stdout.write(result.decode())
 sys.stdout.flush()
 
# P]ͨ
channel.close()
# P]朽
trans.close()

6 ֧tabԄaȫ

import paramiko
import os
import select
import sys
import tty
import termios
 
'''
FһxshellϵyЧ䛵ϵyͲݔͬrؽY
֧Ԅaȫֱ{÷K
'''
# һsocket
trans = paramiko.Transport(('192.168.2.129', 22))
# һ͑
trans.start_client()
 
# ʹrsa耵䛵Ԓ
'''
default_key_file = os.path.join(os.environ['HOME'], '.ssh', 'id_rsa')
prikey = paramiko.RSAKey.from_private_key_file(default_key_file)
trans.auth_publickey(username='super', key=prikey)
'''
# ʹÑܴa
trans.auth_password(username='super', password='super')
# _һͨ
channel = trans.open_session()
# @ȡK
channel.get_pty()
# K@ӾͿԵ䛵Kͺ҂xshellϵyһ
channel.invoke_shell()
 
# @ȡԭKˌ
oldtty = termios.tcgetattr(sys.stdin)
try:
 # FڵIJKˌOÞϵԭKˌ,֧tab
 tty.setraw(sys.stdin)
 channel.settimeout(0)
 
 while True:
 readlist, writelist, errlist = select.select([channel, sys.stdin,], [], [])
 # Ñݔ,sys.stdinl׃
 if sys.stdin in readlist:
  # @ȡݔăݔһַl1ַ
  input_cmd = sys.stdin.read(1)
  # lͽo
  channel.sendall(input_cmd)
 
 # ˽Y,channelͨܵY,l׃ select֪
 if channel in readlist:
  # @ȡY
  result = channel.recv(1024)
  # _BӺ˳
  if len(result) == 0:
  print("\r\n**** EOF **** \r\n")
  break
  # ݔĻ
  sys.stdout.write(result.decode())
  sys.stdout.flush()
finally:
 # 󌢬FڵĽKˌԻ֏͞ԭKˌ
 termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
 
# P]ͨ
channel.close()
# P]朽
trans.close()

@ƪPPython paramiko ?SSHҪģM¾ͽB@,PPython paramiko ?SSHՈ_֮ǰ»^mg[PϣԺ֧_֮

ܸdȤ:

  • ʹPython paramiko?ö߳ʵsshlв
  • Python paramiko?ʹýzʵssh
  • pythonʹparamiko?ͨssh2fhQCMõķ
  • pythonparamiko?ʵsshBӵLinux
  • pythonʹparamiko?ʵsshh̵ςļ

P