前言
本篇博客是python开发的使用案例博客,结合一些具体的案例进行阐述,本篇博客主要内容是使用Python发送Get请求,模拟http请求,后面可以搞个爬虫出来,另外就是如何使用Python进行SSH连接服务器。
其他相关的博客文章如下:
- Python开发——工具篇 & Pycharm的相关配置,Python相关操作 & 持续更新
目录
- 前言
- 引出
- python发送get请求
- 案例1:get请求,间隔1分钟查询,if语法打印
- 案例2:间隔一定时间,轮流进行get请求,总共2个
- python进行SSH链接
- 建立SSH连接核心程序
- 日志打印附件
- 总结
引出
1.使用Python发送Get请求,模拟http请求;
2.如何使用Python进行SSH连接服务器;
python发送get请求
案例1:get请求,间隔1分钟查询,if语法打印
import requests
import time
from datetime import datetimeurl=f'http://x.x.x.x:8082/sn' #格式化输出拼接
snTarget = "S231012J0029"while(True):response = requests.get(url=url) snList = response.json()current_time = datetime.now()if snTarget in snList:print("%s 查询到目标sn" %current_time)else:print("%s 未查到设备sn" %current_time)time.sleep(60)
案例2:间隔一定时间,轮流进行get请求,总共2个
# encoding:utf-8
import requests
import time
from datetime import datetimereq3 = "http://xxxx"
req4 = "http://xxxx"
reqs = [req3, req4]
vers = ["2.0.3", "2.0.4"]
url = f'http://x.x.x.x:8082/sn' # 格式化输出拼接
snTarget = "S231012J0029"while (True):response = requests.get(url=url)snList = response.json()current_time = datetime.now()if snTarget in snList:print("%s 查询到目标sn" % current_time)for ver, req in zip(vers, reqs):print("{} 进行版本升级 {}".format(datetime.now(), ver))# print("send request :", req)resp = requests.get(url=req).json()print(resp)time.sleep(430)else:print("%s 未查到设备sn" % current_time)time.sleep(60)
python进行SSH链接
建立SSH连接核心程序
import paramiko
from paramiko.client import SSHClient
import time
import logging
import utils.LogUtils# 设置日志日期格式
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s', level=logging.DEBUG)# main主方法
def ssh_hi(client: SSHClient):# 执行命令stdin, stdout, stderr = \client.exec_command("grep -E 'RegSWVersion|onResponse' /root/logs/sys-debug.log |grep -v 1.1 | tail -n 1")# 打印命令输出resp = stdout.read().decode()logging.info(resp)if "2.0.4" in resp:logging.warning("当前版本为2.0.4, 版本改为2.0.3")elif "2.0.3" in resp:logging.warning("当前版本为2.0.3, 版本改为2.0.4")else:logging.warning("需要上位机刷新版本")# 关闭连接
def closeSSH(client: SSHClient):client.close()# 建立连接
def buildSSH():# 创建SSH客户端client = paramiko.SSHClient()# 自动添加主机名和密钥到本地的known_hosts文件client.set_missing_host_key_policy(paramiko.AutoAddPolicy())# 连接SSH服务器client.connect('ip', port=22, username='username', password='password')return clientif __name__ == '__main__':ssh = buildSSH()while(True):ssh_hi(ssh)time.sleep(120)# closeSSH(ssh)
日志打印附件
#!/usr/bin/env python
# encoding: utf-8
import logging# now we patch Python code to add color support to logging.StreamHandler
def add_coloring_to_emit_windows(fn):# add methods we need to the classdef _out_handle(self):import ctypesreturn ctypes.windll.kernel32.GetStdHandle(self.STD_OUTPUT_HANDLE)out_handle = property(_out_handle)def _set_color(self, code):import ctypes# Constants from the Windows APIself.STD_OUTPUT_HANDLE = -11hdl = ctypes.windll.kernel32.GetStdHandle(self.STD_OUTPUT_HANDLE)ctypes.windll.kernel32.SetConsoleTextAttribute(hdl, code)setattr(logging.StreamHandler, '_set_color', _set_color)def new(*args):FOREGROUND_BLUE = 0x0001 # text color contains blue.FOREGROUND_GREEN = 0x0002 # text color contains green.FOREGROUND_RED = 0x0004 # text color contains red.FOREGROUND_INTENSITY = 0x0008 # text color is intensified.FOREGROUND_WHITE = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED# winbase.hSTD_INPUT_HANDLE = -10STD_OUTPUT_HANDLE = -11STD_ERROR_HANDLE = -12# wincon.hFOREGROUND_BLACK = 0x0000FOREGROUND_BLUE = 0x0001FOREGROUND_GREEN = 0x0002FOREGROUND_CYAN = 0x0003FOREGROUND_RED = 0x0004FOREGROUND_MAGENTA = 0x0005FOREGROUND_YELLOW = 0x0006FOREGROUND_GREY = 0x0007FOREGROUND_INTENSITY = 0x0008 # foreground color is intensified.BACKGROUND_BLACK = 0x0000BACKGROUND_BLUE = 0x0010BACKGROUND_GREEN = 0x0020BACKGROUND_CYAN = 0x0030BACKGROUND_RED = 0x0040BACKGROUND_MAGENTA = 0x0050BACKGROUND_YELLOW = 0x0060BACKGROUND_GREY = 0x0070BACKGROUND_INTENSITY = 0x0080 # background color is intensified.levelno = args[1].levelnoif (levelno >= 50):color = BACKGROUND_YELLOW | FOREGROUND_RED | FOREGROUND_INTENSITY | BACKGROUND_INTENSITYelif (levelno >= 40):color = FOREGROUND_RED | FOREGROUND_INTENSITYelif (levelno >= 30):color = FOREGROUND_YELLOW | FOREGROUND_INTENSITYelif (levelno >= 20):color = FOREGROUND_GREENelif (levelno >= 10):color = FOREGROUND_MAGENTAelse:color = FOREGROUND_WHITEargs[0]._set_color(color)ret = fn(*args)args[0]._set_color(FOREGROUND_WHITE)# print "after"return retreturn newdef add_coloring_to_emit_ansi(fn):# add methods we need to the classdef new(*args):levelno = args[1].levelnoif (levelno >= 50):color = '\x1b[31m' # redelif (levelno >= 40):color = '\x1b[31m' # redelif (levelno >= 30):color = '\x1b[33m' # yellowelif (levelno >= 20):color = '\x1b[32m' # greenelif (levelno >= 10):color = '\x1b[35m' # pinkelse:color = '\x1b[0m' # normaltry:args[1].msg = color + args[1].msg + '\x1b[0m' # normalexcept Exception as e:pass# print "after"return fn(*args)return newimport platformif platform.system() == 'Windows':# Windows does not support ANSI escapes and we are using API calls to set the console colorlogging.StreamHandler.emit = add_coloring_to_emit_windows(logging.StreamHandler.emit)
else:# all non-Windows platforms are supporting ANSI escapes so we use themlogging.StreamHandler.emit = add_coloring_to_emit_ansi(logging.StreamHandler.emit)# log = logging.getLogger()# log.addFilter(log_filter())# //hdlr = logging.StreamHandler()# //hdlr.setFormatter(formatter())
总结
1.使用Python发送Get请求,模拟http请求;
2.如何使用Python进行SSH连接服务器;