u60f3~548c~4f60~5206~4eab~7684~4e0d~53ea~662f~4e91
一linux传文件到windows,思路-实现目标
要实现定时windows下重要数据上传到远端linux服务器保存,考虑搭建ftp等端口要调整以及网路不准许,所以用python实现。
二linux传文件到windows,涉及的模块作用介绍
1,re模块:该模块包含一些函数,用于处理正则表达式。正则表达式是一种用于匹配字符串模式的工具。比如,你可以使用这个模块来查找文本中的特定模式,或则对文本进行复杂的搜索和替换操作。
import re
# 匹配电子邮件地址的模式
pattern = r'[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+'
text = '我的电子邮件地址是test@test.com'
match = re.search(pattern, text)
if match:
print('找到电子邮件地址:', match.group())
else:
print('未找到电子邮件地址')
2,os模块:这个模块提供了许多与操作系统交互的功能。比如,你可以使用这个模块来创建、读取、写入或删掉文件,也可以获取有关文件系统或当前工作目录的信息。据悉,这个模块还包括一些用于执行外部命令的函数。
import os
# 获取当前工作目录
current_directory = os.getcwd()
print('当前工作目录:', current_directory)
# 创建新目录
os.makedirs('new_directory')
3,configparser模块:这个模块用于解析配置文件。配置文件是一种文本文件,一般用于储存程序或应用程序的配置信息。configparser模块提供了一种简单的方法来读取和解析这种文件中的信息。
import configparser
# 创建一个配置解析器对象
config = configparser.ConfigParser()
# 读取配置文件
config.read('example.ini')
# 获取配置值
section = 'section_name'
option = 'option_name'
value = config.get(section, option)
print('配置值:', value)
4,shutil模块红帽子linux下载,它是Python的标准库的一部份,主要用于中级文件操作。比如,你可以使用这个模块来复制或联通文件和目录,还可以获取文件或目录的信息。
import shutil
# 源目录路径
src = "/path/to/source/directory"
# 目标目录路径
dst = "/path/to/destination/directory"
# 递归复制目录及其内容
shutil.copytree(src, dst)
三,源码码
1,配置文件反例
[linux]
serverdir=/opt/
localdir=D:thispcFworkPycharmProjects
ip=192.168.67.162
user=root
password=123456
port=1536
[myparameter_colony]
info_colony=['192.168.67.153', 'root', 'its312','22'], ['192.168.67.153', 'root', 'its312','22']
2,源代码
import paramiko
import re
from time import sleep
import os, configparser,shutil
config = configparser.ConfigParser()
config.read('config.ini',encoding='utf-8')
lists_header = config.sections()
linux_ip = config.get('linux', 'ip')
linux_user = config.get('linux', 'user')
linux_password = config.get('linux', 'password')
linux_port = config.getint('linux', 'port')
remote_path2 = config.get('linux', 'serverdir')
local_path = config.get('linux', 'localdir')
linux_zoon = config.get('myparameter_colony','info_colony')
# 定义一个类,表示一台远端linux主机
# 参考https://www.cnblogs.com/haigege/p/5517422.html wyc
class Linux(object):
# 通过IP, 用户名,密码,超时时间初始化一个远程Linux主机
def __init__(self, ip, username, password, timeout=3000):
self.ip = ip
self.username = username
self.password = password
self.timeout = timeout
# transport和chanel
self.t = ''
self.chan = ''
# 链接失败的重试次数
self.try_times = 3
# 调用该方法连接远程主机
def connect(self):
while True:
# 连接过程中可能会抛出异常,比如网络不通、链接超时
try:
self.t = paramiko.Transport(sock=(self.ip))
self.t.connect(username=self.username, password=self.password)
self.chan = self.t.open_session()
self.chan.settimeout(self.timeout)
self.chan.get_pty()
self.chan.invoke_shell()
# 如果没有抛出异常说明连接成功,直接返回
print(u'连接%s成功' % self.ip)
# 接收到的网络数据解码为str
print(self.chan.recv(65535).decode('utf-8'))
return
# 这里不对可能的异常如socket.error, socket.timeout细化,直接一网打尽
except Exception as e1:
if self.try_times != 0:
print(u'连接%s失败,进行重试' % self.ip)
self.try_times -= 1
else:
print(u'重试3次失败,结束程序')
exit(1)
# 断开连接
def close(self):
self.chan.close()
self.t.close()
# 发送要执行的命令
def send(self, cmd):
cmd += 'r'
# 通过命令执行提示符来判断命令是否执行完成
p = re.compile(r':~ #')
result = ''
# 发送要执行的命令
self.chan.send(cmd)
# 回显很长的命令可能执行较久,通过循环分批次取回回显
while True:
sleep(0.5)
ret = self.chan.recv(65535)
ret = ret.decode('utf-8')
result += ret
if p.search(ret):
print(result)
return result
# ------获取本地指定目录及其子目录下的所有文件------
def __get_all_files_in_local_dir(self, local_dir):
# 保存所有文件的列表
all_files = list()
# 获取当前指定目录下的所有目录及文件,包含属性值
files = os.listdir(local_dir)
for x in files:
# local_dir目录中每一个文件或目录的完整路径
filename = os.path.join(local_dir, x)
# 如果是目录,则递归处理该目录
if os.path.isdir(x):
all_files.extend(self.__get_all_files_in_local_dir(filename))
else:
all_files.append(filename)
return all_files
def sftp_put_dir(self, local_dir, remote_dir):
t = paramiko.Transport(sock=(self.ip,linux_port))
t.connect(username=self.username, password=self.password)
sftp = paramiko.SFTPClient.from_transport(t)
# 去掉路径字符穿最后的字符'/',如果有的话
if remote_dir[-1] == '/':
remote_dir = remote_dir[0:-1]
# 获取本地指定目录及其子目录下的所有文件
all_files = self.__get_all_files_in_local_dir(local_dir)
# 依次put每一个文件
for x in all_files:
filename = os.path.split(x)[-1]
remote_filename = remote_dir + '/' + filename
print(x)
print(remote_filename)
print(u'Put文件%s传输到%s中...' % (filename, self.ip))
sftp.put(x, remote_filename)
if __name__ == '__main__':
remote_path = remote_path2
local_path = local_path
# host.sftp_put_dir(local_path, remote_path)
#hostArray = [['192.168.67.162', 'root', '123456','22']]
#hostArray = [linux_zoon] # 多台机器配置
hostArray = [[linux_ip, linux_user, linux_password, linux_port]]
for x in hostArray:
host = Linux(x[0], x[1], x[2] ,x[3])
host.sftp_put_dir(local_path, remote_path)
# host.close()
四linux操作系统简介,总结
打包成exe,用windows定时任务运行exe就可以实现定时上传。
最后的最后(Last but not least),欢迎交流:
关注公众号留言,或者在下方直接留言: