当前位置:网站首页>Operate the server remotely more gracefully: the practice of paramiko Library
Operate the server remotely more gracefully: the practice of paramiko Library
2022-07-04 04:37:00 【Software quality assurance】
Continue to adhere to the original output , Click on the blue word to follow me
author : Software quality assurance
You know :https://www.zhihu.com/people/iloverain1024
As a test , If you ask what tools you deal with more in your work , Presumably most people will not hesitate to say server .
Test environment construction 、 Code deployment 、 The problem location log query is inseparable from the operation server . We usually log in to the server to operate the service , Then switch to the corresponding log directory , adopt grep/tail Way to query the logs we want . Of course, there are also many clients on the market to assist us in operating the server , for example xshell/xftp, But even with the client , It is still impossible to minimize our manual pipeline operation . Therefore, this paper introduces an efficient Python library Paramiko, Help you develop your own log query tool .
Paramiko What can be done
paramiko yes Python A library written in language , follow SSH2 agreement , Support the connection of remote server in the way of encryption and authentication , utilize paramiko, It can be done conveniently SSH Connect the server and file transfer between servers .
Paramiko Some basic nouns in :
1. Channel: It's kind of safe SSH Transmission channel ;
2. Transport: When used, an encrypted Tunnels( passageway ), This Tunnels be called Channel;
3. Session: yes Client And Server Keep connected objects , use connect()/start_client()/start_server() Open a session .
How to use Paramiko
Paramiko Provide a wealth of API For our use , This section mainly introduces several commonly used API And how to use it .
pip config set global.index-url https://mirrors.aliyun.com/pypi/simple/pip install paramiko
1. Establishing a connection
paramiko.connect Detailed explanation of method parameters :
connect Common parameters
hostname Connected target host
port=SSH_PORT Designated port
username=None The verified user name
password=None Authenticated user password
pkey=None Private key mode is used for authentication
key_filename=None A file name or list of files , Specify private key file
timeout=None Optional tcp Connection timeout
allow_agent=True, Allow connection to ssh agent , The default is True allow
look_for_keys=True Whether in ~/.ssh Search for private key file , The default is True allow
compress=False, Whether to turn on compression
Method 1 、 Password connection server
import paramikofrom paramiko import SSHClientdef connect_with_password(host, username, password):ssh = paramiko.SSHClient()# Auto add policy , Save the host name and key information of the server , If you do not add , So it's no longer local know_hosts The host recorded in the file will not be able to connectssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())ssh.load_system_host_keys()ssh.connect(host, username=username,password=password)session = ssh.get_transport().open_session()AgentRequestHandler(session)ssh_stdin, ssh_stdout, ssh_stderr = session.exec_command("ls -l")content = ssh_stdout.read()return session
Method 2 、 Key connection server
def connect_with_RSAKey(host, username, file):# Configure private key file locationprivate = paramiko.RSAKey.from_private_key_file(file)# private = paramiko.RSAKey.from_private_key_file('/Users/qa/.ssh/id_rsa')ssh = paramiko.SSHClient()ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())# Connect SSH Server side , Authenticate with user name and passwordssh.connect(hostname=host, port=22, username=username, pkey=private)session = ssh.get_transport().open_session()AgentRequestHandler(session)ssh_stdin, ssh_stdout, ssh_stderr = session.exec_command("ls -l")content = ssh_stdout.read()return session
2. Carry out orders
Use exec_command Executing the command will return three messages :
1、 Standard inputs ( Used to implement interactive commands )--stdin
2、 standard output ( Save the normal execution result of the command )--stdout
3、 Standard error output ( Save the error message of the command )--stderr
# Defined function ssh, Write the operation contents into the functiondef ssh_exe_cmd(host, username, password, content):session = connect_with_password(host, username, password)# Use exec_command Method to execute the command , And use variables to receive the return value of the command and use print Outputstdin, stdout, stderr = session.exec_command(content)return stdout.read()
3. Upload and download
Like we use xshell Executing instructions on the server is the same as querying logs , We can be like xftp Upload and download files on the server .
# File downloaddef download_file_ftp(host, username, password, local_path, remote_path):# Create with the server ssh Connect ,transport Methods establish channels , Write server information in tuplesssh_ftp = paramiko.Transport((host, 60317))ssh_ftp.connect(username=username, password=password)# After creating a connection , Use sftpclient Classes and from_transport( In parentheses, write the one created above Transport passageway ) Based on the above ssh Create a connection sftp Connect , Defined as ftp_client Variables are easy to referenceftp_client = paramiko.SFTPClient.from_transport(ssh_ftp)# Download the file#ftp_client.get(" Target file ", r" Save the location , Write file name ")ftp_client.get(remote_path, local_path)# close ssh Connectssh_ftp.close()# Upload filesdef upload_file_ftp(host, username, password, local_path, remote_path):# Create with the server ssh Connect ,transport Methods establish channels , Pause server information in tuplesssh_ftp = paramiko.Transport((host, 60317))ssh_ftp.connect(username=username, password=password)# After creating a connection , Use sftpclient Classes and from_transport( In parentheses, write the one created above Transport passageway ) Based on the above ssh Create a connection sftp Connect , Defined as ftp_client Variables are easy to referenceftp_client = paramiko.SFTPClient.from_transport(ssh_ftp)# Upload filesftp_client.put(local_path, remote_path)# close ssh Connectssh_ftp.close()
be based on Paramiko Develop log query tools
The implementation principle is very simple , Is to automatically disconnect the server ( logon server ) Part of , The execution tool automatically connects to the server , Users only need to enter the log query instruction . The complete code is as follows :
# -*- coding: utf-8 -*-# @Author : qualityassurance# @Email : [email protected]# @File : ParamikoUtil.py# @Time : 2022/7/3 11:13import paramikofrom paramiko.agent import AgentRequestHandlerhost = ''port = ''username = ''password = ''def connect_with_password(host, port, username, password):""" Connect to server ,Client = paramiko.SSHClient()"""ssh = paramiko.SSHClient()try:ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())ssh.load_system_host_keys()ssh.connect(host, port=port, username=username,password=password)except Exception as e:print(e)return sshdef ssh_exe_cmd(client, cmd):""" Return the command result executed remotely :stdin, stdout, stderr (stdout) and decode Output ..."""stdin, stdout, stderr = client.exec_command(cmd)print(stdout.read().decode())return stdoutdef main():""" Set remote execution Linux Operation command input ..."""client = connect_with_password(host, port, username, password)while True:cmd = input(" Enter the command to be executed ( Empty to exit ):").strip()if cmd == "":return Falseelse:ssh_exe_cmd(client, cmd)if __name__ == "__main__":main()
Like it , Just click on it. Zanhe is looking at Let's go
- END -
Scan the code below to pay attention to Software quality assurance , Learn and grow with quality gentleman 、 Common progress , Being a professional is the most expensive Tester!
Previous recommendation
Talk to self-management at work
Experience sharing | Test Engineer transformation test development process
Chat UI Automated PageObject Design patterns
边栏推荐
- What is context?
- Y55. Chapter III kubernetes from entry to proficiency -- HPA controller and metrics server (28)
- FT2000+下LPC中断绑核使用说明
- Operation of ES6
- 普源DS1000Z系列数字示波器在通信原理实验中的应用方案
- Senior developers tell you, how to write excellent code?
- Redis: operation command for collecting set type data
- Pytest basic self-study series (I)
- 苹果CMS仿西瓜视频大气响应式视频模板源码
- 【微信小程序】好看的轮播图组件
猜你喜欢

普源DS1000Z系列数字示波器在通信原理实验中的应用方案

Leetcode skimming: binary tree 08 (maximum depth of n-ary tree)

Dp83848+ network cable hot plug

Select function variable column name in dplyr of R language

Statistical genetics: Chapter 3, population genetics

leetcode:1314. 矩阵区域和【二维前缀和模板】

【微信小程序】好看的轮播图组件

R语言中如何查看已安装的R包

rac删除损坏的磁盘组

Senior developers tell you, how to write excellent code?
随机推荐
Application scheme of Puyuan ds1000z series digital oscilloscope in communication principle experiment
Rhcsa 01 - create partitions and file systems
Operation of ES6
[Yugong series] go teaching course 002 go language environment installation in July 2022
Architecture practice camp - graduation project of module 9 of phase 6
Emlog用户注册插件 价值80元
Distributed cap theory
Keysight N9320B射频频谱分析仪解决轮胎压力监测方案
精品网址导航主题整站源码 wordpress模板 自适应手机端
rac删除损坏的磁盘组
What does software testing do? Find defects and improve the quality of software
Use NRM and NVM to manage your NPM source and node versions
R语言dplyr中的Select函数变量列名
Why use node
架构实战营 - 第 6 期 模块九之毕业设计
Instructions for LPC interrupt binding under ft2000+
6-5漏洞利用-SSH弱口令破解利用
深入解析结构化异常处理(SEH) - by Matt Pietrek
Leetcode brush questions: binary tree 05 (flip binary tree)
EIG在智利推出可再生能源平台Grupo Cerro