Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the method for Python to log on to the server remotely

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains the "Python remote login server method is what", the content of the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "Python remote login server method is what" it!

In a shell environment, this is what we do.

$sshpass-p ${passwd} ssh-p ${port}-l ${user}-o StrictHostKeyChecking=no xx.xx.xx.xx "ls-l"

Then you will find that your output has a lot of information that you don't need but can't get away (maybe there is a way, please leave a message to communicate), like this.

Host: xx.xx.xx.xx, port: xx Warning: Permanently added'[xx.xx.xx.xx]: xx' (RSA) to the list of known hosts. Login failure: [Errno 1] This server is not registered to rmp platform, please confirm whether cdn server. Total 4-rw-r--r-- 1 root root 239 Mar 30 2018 admin-openrc

For those who directly use the shell command to execute the command, you can directly use the pipe or redirect the standard output to a file to obtain the result returned by executing the command.

1. Use subprocess

If we use Python to do this, we usually immediately think of using some commands such as os.popen,os.system,commands,subprocess to execute the library to get it indirectly.

But as far as I know, the output obtained by these libraries is not only standard output, but also standard error (that is, the redundant information above).

So we have to clean the data of output every time, and then organize and format it in order to get the data we want.

Take subprocess, for example, like this.

Import subprocess ssh_cmd = "sshpass-p ${passwd} ssh-p 22-l root-o StrictHostKeyChecking=no xx.xx.xx.xx'ls-l'" status, output = subprocess.getstatusoutput (ssh_cmd) # data cleaning, formatted ones are not shown

Through the above text + code display, you can feel several major pain points of ssh login.

Pain point 1: additional installation of sshpass is required (if not secret-free)

Pain point 2: too much interference information, data cleaning, formatting is quite troublesome

Pain point 3: the code implementation is not elegant (a little corny) and its readability is too poor.

Pain point 4: ssh connections cannot be reused and can only be performed once at a time

Pain point 5: the code cannot be used on the whole platform and can only be used on Linux and OSX

In order to solve these problems, I searched the articles about Python ssh all over the network and did not see any full introduction of these skills.

To this end, I flipped through a very popular Github project: awesome-python-cn (https://github.com/BingmingWong/awesome-python-cn).

Look forward to finding some useful libraries about remote connections here.

I really found two.

Sh.ssh

Paramiko

two。 Use sh.ssh

First, let's introduce the first one, sh.ssh.

Sh is a library that allows you to complete Linxu/OSX system commands through function calls. It is very easy to use, and you have the opportunity to write an introduction to it.

$python3-m pip install sh

Today I will only introduce one of its functions: ssh

Usually two machines visit each other, for convenience, can be set secret-free login, so that there is no need to enter a password.

This code enables secret-free login and executes our command ls-l

From sh import ssh output=ssh ("root@xx.xx.xx.xx", "- p 22", "ls-l") print (output)

But it is possible that we do not want to set up mutual trust immunity, in order to make this code more general, I assume that we do not set it, we can only log in with a password.

Here comes the problem: if you want to enter a password, you have to use an interactive method to enter it. How to achieve it in Python?

It turns out that the ssh method receives a _ out parameter, which can be a string representing the file path, a file object (or a class file object), or a callback function, meaning that when there is standard output, the output will be called to this function.

It's easy to do.

As long as I recognize the word password:, I will write my password to the standard input.

The complete code is as follows:

Import sys from sh import ssh aggregated = "" def ssh_interact (char, stdin): global aggregated sys.stdout.write (char.encode ()) sys.stdout.flush () aggregated + = char if aggregated.endswith ("password:"): stdin.put ("you_password\ n") output=ssh ("root@xx.xx.xx.xx", "- p 22", "ls-l", _ tty_in=True, _ out_bufsize=0, _ out=ssh_interact) print (output)

This is a demo based on some information from the official document (http://amoffat.github.io/sh/tutorials/interacting_with_processes.html?highlight=ssh)).

After trying to run, it is found that the program will always be running, will never return, will not exit, and the callback function will never enter.

Through debugging to see the source code, still can not find the problem, so went to the Github search, originally in 2017 this problem has not been fixed, now 2020 has not been fixed, it seems that there are not many people using sh.ssh, so I also "ask", looking forward to get a reply.

The above problem occurs only when you need to enter a password, and there is no problem if you set up machine mutual trust.

In order to feel the effect of sh.ssh, I set up machine trust immunity, and then use the following code.

From sh import ssh my_server=ssh.bake ("root@xx.xx.xx.xx", "- p 22") # is equivalent to executing the login command one at a time, and then exiting the login print (my_server.ls ()) # during sleep, manually log in to the server and use top to see how many terminals are currently connected to time.sleep (5) # when the command is executed again, the number of login terminals will be + 1. Add-1 print (my_server.ifconfig ())

Surprised to find that using bake this way, my_server.ls () and my_server.ifconfig () seem to be through the same ssh connection, execute the command twice, but in fact, you can execute the top command on the remote machine to see the change of the connected terminal, will first + 1 and then-1, indicating that the execution of the two commands is achieved through two connections.

From this point of view, using sh.ssh can solve pain point 1 (if the above problems can be solved), pain point 2, pain point 3.

But it is still unable to reuse ssh connections, it is still not very convenient, and it is not my ideal excellent solution.

The most important thing is that the sh module only supports Linxu/OSX. In Windows, you have to use its brother library-pbs, and then I went to pypi to take a look at pbs, which is "out of repair" and no one has maintained it.

At this point, from the "pawn", I am short of the last straw.

3. Use paramiko

With a last glimmer of hope, I tried to use the library paramiko, and finally found the elegance that should belong to Python here in paramiko.

You can install it with the following command

$python3-m pip install paramiko

Then, several commonly used methods of ssh login are introduced.

Method 1: sshclient login based on user name and password

Then you can refer to the following code to make a remote connection under the Linux/OSX system

Import paramiko ssh = paramiko.SSHClient () # allow connection to hosts ssh.set_missing_host_key_policy (paramiko.AutoAddPolicy ()) that is not in the know_hosts file # establish a connection ssh.connect ("xx.xx.xx.xx", username= "root", port=22, password= "you_password") # use this connection to execute commands ssh_stdin, ssh_stdout Ssh_stderr = ssh.exec_command ("ls-l") # get output print (ssh_stdout.read ()) # close connection ssh.close ()

Method 2: transport login based on user name and password

Method 1 is a traditional operation of connecting to the server, executing commands, and closing. Multiple operations require multiple connections and cannot be reused [pain point 4].

Sometimes you need to log in to the server to perform multiple operations, such as executing commands and uploading / downloading files, but method 1 cannot be implemented, so you can use the transport method.

Import paramiko # establish a connection trans = paramiko.Transport (("xx.xx.xx.xx", 22)) trans.connect (username= "root", password= "you_passwd") # specify the transport of the object of sshclient as above trans ssh = paramiko.SSHClient () ssh._transport = trans # the rest is the same as above ssh.set_missing_host_key_policy (paramiko.AutoAddPolicy () ssh_stdin, ssh_stdout) Ssh_stderr = ssh.exec_command ("ls-l") print (ssh_stdout.read ()) # close the connection trans.close ()

Method 3: SSHClient login based on public key

Import paramiko # specify the local RSA private key file # if the key pair is set with a password, password is the set password If you do not specify the password parameter pkey= paramiko.RSAKey.from_private_key_file ('/ home/you_username/.ssh/id_rsa', password='12345') # establish a connection ssh = paramiko.SSHClient () ssh.connect (hostname='xx.xx.xx.xx', port=22, username='you_username', pkey=pkey) # execute the command stdin, stdout Stderr = ssh.exec_command ('ls-l') # the result is put into stdout If there is an error, put it in stderr print (stdout.read ()) # close the connection ssh.close ()

Method 4: Transport login based on key

Import paramiko # specify the local RSA private key file # if the key pair is set with a password, password is the set password If you do not specify the password parameter pkey= paramiko.RSAKey.from_private_key_file ('/ home/you_username/.ssh/id_rsa', password='12345') # establish a connection trans = paramiko.Transport (('xx.xx.xx.xx', 22)) trans.connect (username='you_username', pkey=pkey) # specify the transport of the object of sshclient as the above trans ssh = paramiko.SSHClient () ssh._transport = trans # execute the command As with traditional methods, stdin, stdout, stderr = ssh.exec_command ('df-hl') print (stdout.read (). Decode ()) # close the connection trans.close ()

The above four methods can help you to remotely log in to the server to execute commands. If you need to reuse the connection, you can use method 2 and method 4 to execute commands multiple times at a time.

Remember to close the connection after you use it.

Realize sftp file transfer

At the same time, paramiko as the perfect solution for ssh, it is very professional, it can also be used to achieve sftp file transfer.

Import paramiko # instantiate a trans object # instantiate a transport object trans = paramiko.Transport (('xx.xx.xx.xx', 22)) # establish a connection trans.connect (username='you_username', password='you_passwd') # instantiate a sftp object, specify the connection channel sftp = paramiko.SFTPClient.from_transport (trans) # send the file sftp.put (localpath='/tmp/11.txt' Remotepath='/tmp/22.txt') # download file sftp.get (remotepath='/tmp/22.txt', localpath='/tmp/33.txt') trans.close ()

At this point, Paramiko has won a complete victory, but there is still a pain point that we have not mentioned, that is, multi-platform, that is, Windows, there is a good thing and a bad thing.

The good thing is: paramiko supports windows

The bad thing is: you need to do a lot of complicated preparation, you can google to solve, but I suggest you just give up, the hole is too deep.

Thank you for your reading, the above is the content of "what is the method of Python remote login server". After the study of this article, I believe you have a deeper understanding of what the method of Python remote login server is, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report