Python tool authoring Paramiko for SSH remote connection

Source: Internet
Author: User
Tags stdin

There are three ways to implement a client:

1: Login with account password

1.1 Execute the command directly on the server using the Sshclient object's Exec_command ():

Code implementation:

Import Paramiko
Import Sys

Def Usage ():
print "[usage]./ssh_client.py IP Port Command]


Try
IP=SYS.ARGV[1]
Port=int (Sys.argv[2])
COMMAND=SYS.ARGV[3]
Except
Usage ()


User= "Root"
passwd= "Root"
#实例化SSHClient
Client=paramiko. Sshclient ()
#自动添加策略, save the host name and key information for the server
#用ssh连接远程主机时, the first connection will be prompted whether to continue the remote connection, select Yes this sentence will automatically select Yes
Client.set_missing_host_key_policy (Paramiko. Autoaddpolicy ())
#连接SSH服务端, authenticate with user name and password
Client.connect (IP,PORT,USERNAME=USER,PASSWORD=PASSWD)
#打开一个Channel and execute the command
Stdin,stdout,stderr=client.exec_command (command)
#打印执行结果 If there is an error stderr.read () is not empty
If stderr.read () = = "":
For I in Stdout.readlines ():
Print I
Client.close ()

1.2 Instantiate the Sshclient object and get a transport object to execute the command on the server with the transport object's Exec_command ()

Import Sys
Import Paramiko

Def Usage ():
print "[usage]./ssh_client.py IP Port Command]


Try
IP=SYS.ARGV[1]
Port=int (Sys.argv[2])
COMMAND=SYS.ARGV[3]
Except
Usage ()

# reload (SYS)
# sys.setdefaultencoding (' Utf-8 ')
User= "Root"
passwd= "Root"
#实例化SSHClient
Client=paramiko. Sshclient ()
#自动添加策略, save the host name and key information for the server
#用ssh连接远程主机时, the first connection will be prompted whether to continue the remote connection, select Yes this sentence will automatically select Yes
Client.set_missing_host_key_policy (Paramiko. Autoaddpolicy ())
#连接SSH服务端, authenticate with user name and password
Client.connect (IP,PORT,USERNAME=USER,PASSWORD=PASSWD)
#实例化Transport Establishing session Sessions
Ssh_session=client.get_transport (). Open_session ()
If ssh_session.active:
Ssh_session.exec_command (command)
Print SSH_SESSION.RECV (4096)
Client.close ()

2: Log in with the key

Import Paramiko
Import Sys

Def Usage ():
print "[usage]./ssh_client.py IP Port Command]


Try
IP=SYS.ARGV[1]
Port=int (Sys.argv[2])
COMMAND=SYS.ARGV[3]
Except
Usage ()

User= "Root"

#实例化SSHClient
Client=paramiko. Sshclient ()
#指定用来解密的私钥的路径, you need to manually generate
Pkey_file = '/home/.ssh/id_rsa '
#使用私钥解密
Key = Paramiko. Rsakey.from_private_key_file (Pkey_file)
#load_system_host_keys用于指定对方主机存放本机公钥的位置, the default parameter is to set this location to ~/.ssh/known_hosts
Client.load_system_host_keys ()
#自动添加策略, save the host name and key information for the server
#用ssh连接远程主机时, the first connection will be prompted whether to continue the remote connection, select Yes this sentence will automatically select Yes
Client.set_missing_host_key_policy (Paramiko. Autoaddpolicy ())
#连接SSH服务端, authenticate with user name and password
Client.connect (ip,port,username=user,key_filename=key,timeout=6)
#打开一个Channel and execute the command
Stdin,stdout,stderr=client.exec_comment (command)
#打印执行结果 If there is an error stderr.read () is not empty
If stderr.read () = = "":
Print Stdout.readlines ()
Client.close ()

Implement upload and download:

Import Paramiko
#获取Transport实例 parameter is tuple
Tran = Paramiko. Transport (("192.168.72.130", 22))
#连接SSH服务端
Tran.connect (username = "root", password = "root")
#获取SFTP实例
SFTP = Paramiko. Sftpclient.from_transport (Tran)
#设置上传的本地/Remote file path
#执行上传动作
Sftp.put ("C:/7.der", "/tmp/7.der")
Sftp.get ('/root/test.py ', ' f:/test.py ')
Tran.close ()

Issues that occur during the implementation:

Import Paramiko appears unicodedecodeerror: ' ASCII ' codec can ' t decode byte 0xe9 in position 0:ordinal not in range (128) error

Workaround: Under the Python installation path lib\site.py add the following code:

Import Sys

Reload (SYS)

Sys.setdefaultencoding (' GBK ')

The test settings are encoded as Utf-8 or the import is not successfully set to GBK can be imported successfully

The key required to log in is manually generated: you can refer to

Http://blog.sina.com.cn/s/blog_7ae2408501018xsj.html

http://blog.csdn.net/fdipzone/article/details/47327183

Python tool authoring Paramiko implementing SSH remote connection

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.