recently, i need ssh to a remote server, it may be common to everybody with a xshell or mobaxterm, but if you want undertask some commands automatically, you should know how to ssh a remote server by programing. python alrealy provide a strong tool, that`s today`s topic paramiko.
first, you should know how to install it, it`s easy, pip install paramiko, that`s all.
sencod, consider that whether you need proxy to contact you remote server or not, if so, you need another the thrid library called PySocks, it`s easy, pip install PySocks, that`s
thrid, decorate your socket with proxy. codes are here:
#!/usr/bin/env python
#__*utf-8*__
import socks
import socket
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, 'proxy_ip', 8080, True, 'username', 'passwd')
socket.socket =socks.socksocket
attention, you should use proper proxy_type, for example, if you proxy type is HTTP, then you should write socks.PROXY_TYPE_HTTP, the ip and port should be right, if use the proxy need user name & password, you also should write them.
then, we begin to use paramiko,
#!/usr/bin/env python
#__*utf-8*__
import socks
import socket
import paramiko
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, 'proxy_ip', 8080, True, 'username', 'passwd')
socket.socket =socks.socksocket
# variable above will not as params to be used by next code
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
pkey = paramiko.RSAKey.from_private_key_file('private key file path', password='pkey password')
client.connect('ip', port, 'username', pkey=pkey)
so far, we build a ssh client which use private key through a proxy site. next, i will talk how to continue undertask comands, you have better know how to use threading and paramiko invoke_shell()。