python remotely executes SSH command based on paramiko library to realize sftp download file

  • 2021-09-20 20:58:53
  • OfStack

Catalog wedge
paramiko
Use of SSHClient
connect: Connecting and authenticating remote server set_missing_host_key_policy: Coping strategy when remote server does not have local secret key or HostKeys object. Currently, three kinds are supported: exec_command: The use of specific Linux command SFTPClient executed remotely

Wedge

When we use Python, we can't avoid dealing with Linux, and sometimes we need to execute a few shell commands. If it is local, it can be executed by calling os. system or subprocess. Popen, but what should we do at this time if we want to execute the shell command on other machines remotely? Let's recommend a third-party library, paramiko, to see how to use Python to operate other machines remotely.

paramiko

Network transmission follows protocols, for example, SSH and paramiko are an Python third-party library that implements SSHv2 protocol (cryptography is used at the bottom). With paramiko, we can use SSH protocol to connect remote servers to perform operations through Python, which is essentially similar to xshell.

Note: In the Python code, we operate on the remote server directly through the SSH protocol, instead of calling the ssh command.

Since you want to use it, you should install it first, just pip install paramiko.

paramiko contains two core components: SSHClient and SFTPClient

SSHClient acts like the ssh command under Linux, encapsulates an SSH session, and is typically used to execute remote commands.

The function of SFTPClient is similar to the sftp command under Linux, which is the encapsulation of SFTP client and is used to realize the operation of remote files. For example: file upload, download, modify file permissions and other operations.

Let's introduce their usage.

Use of SSHClient

First create a client instance, client = paramiko. SSHClient (), and then there are many methods under this client.

connect: Connecting and Authenticating Remote Server

def connect(
 self,
 hostname,
 port=SSH_PORT,
 username=None,
 password=None,
 pkey=None,
 key_filename=None,
 timeout=None,
 allow_agent=True,
 look_for_keys=True,
 compress=False,
 sock=None,
 gss_auth=False,
 gss_kex=False,
 gss_deleg_creds=True,
 gss_host=None,
 banner_timeout=None,
 auth_timeout=None,
 gss_trust_dns=True,
 passphrase=None,
 disabled_algorithms=None,
):
 """"""

There are many parameters, but the commonly used parameters are as follows:

hostname: The destination host of the connection, this parameter is required port=SSH_PORT: The specified port, default is 22 username=None: Login user password=None: User password pkey=None: Authentication with private key key_filename=None: 1 file name or file list specifying the private key file timeout=None: Optional tcp connection timeout allow_agent=True: Allow connection to ssh proxy, default to True look_for_keys=True: Whether to search for private key file in ~/. ssh, default to True, indicating allowed compress=False: Turn on compression

set_missing_host_key_policy: Three strategies are currently supported when the remote server does not have a local secret key or HostKeys object: AutoAddPolicy: Automatic addition of host name and host secret key to local HostKeys object, independent of load_system_host_key configuration, i.e. yes or no is not required for confirmation when new ssh connection is established WarningPolicy: An Python alert for an unknown host key is logged and received; So its functionality is similar to that of AutoAddPolicy, except that it will be prompted that this is a new connection RejectPolicy: Automatically reject unknown hostname and secret key, depending on the configuration of load_system_host_key, this option is the default option

Therefore, we will always change the policy to AutoAddPolicy, otherwise we need to configure it locally.

exec_command: A concrete Linux command to execute remotely

open_sftp: Create an sftp session on the basis of the current ssh session. This method will return an SFTPClient object, which can upload and download files. We will talk about it later in SFTPClient.

Let's demonstrate 1:


import paramiko

#  Instantiation  SSHClient
client = paramiko.SSHClient()

#  Automatically add policies ,  Save the host name and key information of the server ;  If you do not add ,  Then it's no longer local  know_hosts  The host in the file will not be able to connect 
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

#  Connect  SSH  Server side ,  Authentication by username and password 
#  This procedure creates a 1 A  session,  It is  client  And  server  Objects that remain connected 
client.connect(hostname='47.94.174.89', port=22, username='root', password='xxxxxxx')

#  Execute remote commands ,  This method opens the 1 A  paramiko.Channel  Object ( Class  socket, 1 A kind of safe  SSH  Transmission channel )
#  Will return 3 Values ,  They are  stdin( Standard input ) , stdout( Standard output ) , stderr( Error output )
stdin, stdout, stderr = client.exec_command("ls /")

#  Print execution results ,  Apparently we're going through  stdout  To view ,  We can call  stdout.read  Get the results of execution 
#  But it returns bytes ,  So you need to get the corresponding code first ,  And then proceed  decode
print(stdout.read().decode("utf-8"))
"""
bin
boot
dev
etc
home
lib
lib64
lost+found
media
mnt
opt
proc
root
run
sbin
srv
sys
tmp
usr
var

"""
#  Final closure  SSHClient  Object 
client.close()

It's still very simple. If we type an incorrect command, there will be no content in stdout, because the error message will be saved in stderr.


import paramiko

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname='47.94.174.89', port=22, username='root', password='xxxxxxx')
stdin, stdout, stderr = client.exec_command("xxxxx")
print(stderr.read().decode("utf-8"))
"""
bash: xxxxx: command not found

"""
client.close()

Use of SFTPClient

SFTPClient is a client object of sftp. According to the sftp session of ssh transport protocol, it can realize the operation of remote files, such as uploading, downloading, viewing authority and status, etc.


import paramiko

#  Create 1 A  Transport  Object ,  Is created synchronously when used 1 A  paramiko.Channel  Object 
#  Parameter passing 1 By  IP  And  PORT  To form a tuple 
transport = paramiko.Transport(("47.94.174.89", 22))

#  Connect  ssh,  Pass  username  And  password
transport.connect(username="root", password="xxxxxxx")

#  Get  SFTPClient  Instances ,  It is equivalent to  Linux  Under  sftp,  Through it, we can carry out the file 1 Some operations 
sftp = paramiko.SFTPClient.from_transport(transport)

We got sftp above, so what operations does it support?

put (self, localpath, remotepath, callback=None, confirm=True): Upload the local file to the server, and callback means the callback function, which is called after successful uploading; confirm indicates whether the stat method is called to check the file status and returns the result of ls-l get (self, remotepath, localpath, callback=None): Download files from server to local mkdir (self, path, mode=o777): Creates a directory on the server where mode represents permissions and defaults to 511 (o777 is a variable equal to 511) rmdir (self, path): Delete directories on the server remove (self, path): Delete files on the server rename (self, oldpath, newpath): Rename the directory on the server stat (self, path): View the status of a file or directory listdir (self, path= '.'): Lists files in the server directory getcwd (self): View the workspace, which is the current path chmod (self, path, mode): Changing Permissions chown (self, path, uid, gid): Changing Users and Groups chdir (self, path): Changing the workspace

Commonly used about the above, let's demonstrate 1.


# 1.  Change the workspace 
sftp.chdir("/usr/local/bin")

# 2.  View the workspace 
print(sftp.getcwd()) # /usr/local/bin
sftp.chdir("/root")
print(sftp.getcwd()) # /root
"""
 If you do not call  sftp.chdir(path)  At the time of ,  Then print  sftp.getcwd()  The result is  None
 But we know that landing  Linux  Hour ,  By default, it will be in  /root  Directory ( For  root  As far as users are concerned )
 For the current  sftp  That's true in terms of ,  Just print  sftp.getcwd()  The result is  None  Just  
"""

# 3.  List the files in the current directory 
print(sftp.listdir("/usr/local")) # ['lib', 'lib64', 'games', 'aegis', ...]

# 4.  View file or directory status 
print(sftp.stat("/root/.ssh/authorized_keys"))
"""
-rw------- 1 0  0    0 16 Dec 13:26 ?
"""

# 5.  Change permissions 
sftp.chmod("/root/.ssh/authorized_keys", 0o777)
print(sftp.stat("/root/.ssh/authorized_keys"))
"""
-rwxrwxrwx 1 0  0    0 16 Dec 13:26 ?
"""

# 6.  Create Directory 
print("dir" in sftp.listdir("/root")) # False
sftp.mkdir("/root/dir", mode=0o777)
print("dir" in sftp.listdir("/root")) # True

# 7.  Delete Directory 
sftp.rmdir("/root/dir")
print("dir" in sftp.listdir("/root")) # False

# 8.  Delete a file 
sftp.remove("/root/1.py")

# 9.  Download a file 
sftp.get("/root/makefile", r"makefile")

# 10.  Upload a file 
sftp.put("dockerfile", "/root/dockerfile")

#  Final closure  sftp  And  transport
sftp.close()
transport.close()

Of course, as we said when we introduced SSHClient, we can also create sftp clients by open_sftp.


import paramiko

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname='47.94.174.89', port=22, username='root', password='xxxxxxx')
#  It is also possible to create it in this way 
sftp = client.open_sftp()

The above is python based on paramiko library remote execution of SSH command, sftp download file details, more information about python paramiko library please pay attention to other related articles on this site!


Related articles: