0

我必须创建一个连接到 MS-SQL DB 的 Python 脚本(这已完成并提取我需要的信息),并从表中提取 IP 地址列表并使用它来完成服务器路径以搜索特定文件在每个服务器上,然后对该文件的 5 个参数进行修改,然后跳转到下一个服务器并进行相同的更改,依此类推。任何对迭代创建的帮助都将非常受欢迎目前我所拥有的是:

import pyodbc
####   --->>>Connection to SQL Server
conn = pyodbc.connect('Driver={SQL Server};'
                          'Server=****Mi servidor****;'
                          'UID=***Usuario****;'
                          'PWD=***password***;'
                          'database=voiceData;'
                          'Trusted_Connection=yes;'
                          )

cursor = conn.cursor()
cursor.execute('EXECUTE dbo.GET_localOfficeAvayaFilePaths')


####  --->>>Changes on the 46xxsettings.txt file
for row in cursor:
    print('', row[3])
    string_map = {'## SET SLMSRVR': 'SET SLMSRVR 192.168.1.1', 
                  '## SET SLMSTAT 1': 'SET SLMSTAT 1',
                  '## SET SLMPERF 1': 'SET SLMPERF 1',
                  '## SET SLMCAP 1': 'SET SLMCAP 2',
                  'SET SLMCTRL 1': 'SET SLMCTRL 1'}

    for line in cursor.readlines():
        if line.startswith('## SET'):
            for original, new in string_map.items():
                if original in line:
                    line = new
                    break
        print(line.strip())

cursor.close()
del cursor
4

1 回答 1

0

我不完全确定您要达到的目标,

如果您正在查询数据库以获取 5 个 IP 地址的列表,假设您将其保存到名为“ips_list”的变量中,

然后,正如您所说,您想为 IP 地址添加一个恒定路径并下载文件,

然后编辑(我假设)该配置文件中的 5 行,

你没有提到你打算用那个文件做什么,为了简单起见,我只是用适当的名字保存了它。

看看下面的代码:

import urllib.request

FILE_PATH = "http://{}/path/to/file.ini"
STRING_MAP = {"## SET SLMSRVR": "SET SLMSRVR 192.168.1.1", 
        "## SET SLMSTAT 1": "SET SLMSTAT 1",
        "## SET SLMPERF 1": "SET SLMPERF 1",
        "## SET SLMCAP 1": "SET SLMCAP 2",
        "SET SLMCTRL 1": "SET SLMCTRL 1"}

def func(ips_list):
    for ip_address in ips_list: # Assume: type(ip_address) == str
        conf_file = urllib.request.urlopen(FILE_PATH.format(ip_address)).read() # You should handle exceptions
        with open("./conf_files/{}/.ini".format(ip_address), "w", encoding="utf8") as outfile:
            for line in conf_file.splitlines():
                for key in STRING_MAP:
                    if line.startswith(key):
                        line = STRING_MAP[key]
                        break
                outfile.write(line)
于 2019-03-28T18:36:00.200 回答