Python-检查网络映射

Python-检查网络映射,python,Python,我正在寻找一些逻辑方面的帮助,代码不是很像Python,我还在学习。我们始终将Z:驱动器映射到不同的位置。这就是我想要实现的目标 1:在Z:say\192.168.1.100\old上检查旧地图 2:将新位置映射到Z:say\192.168.1.200\new 3:确保新的Z:映射存在且仍处于连接状态 4:如果断开连接或未映射,请重新连接并记录 90%的代码可以工作,如果我按原样运行,它会取消映射旧驱动器并映射新驱动器,但旧驱动器的名称保持不变,即使它映射到新位置,我也可以浏览它。另一个问题是我

我正在寻找一些逻辑方面的帮助,代码不是很像Python,我还在学习。我们始终将Z:驱动器映射到不同的位置。这就是我想要实现的目标

1:在Z:say\192.168.1.100\old上检查旧地图
2:将新位置映射到Z:say\192.168.1.200\new
3:确保新的Z:映射存在且仍处于连接状态
4:如果断开连接或未映射,请重新连接并记录

90%的代码可以工作,如果我按原样运行,它会取消映射旧驱动器并映射新驱动器,但旧驱动器的名称保持不变,即使它映射到新位置,我也可以浏览它。另一个问题是我只想运行一次checkOldDrive,然后让checkDrive运行。任何建议都将不胜感激

#!/usr/bin/python
import pywintypes
import win32com.client
import os.path
import sys
import string
import fileinput
import time
import win32net
##################################################################
# Check for old Z: map and remove it
# Map the new instance of Z:
# Check if the Z: drive exists
# if the drive exists report to status.log we are working
# if the drive DOES NOT exist map it and report errors to the log
###################################################################
def checkDrive():
    if os.path.exists('z:'):
        saveout = sys.stdout
        fsock = open('status.log', 'a')
        sys.stdout = fsock
        print os.getenv("COMPUTERNAME"), " - ", time.ctime(), " - Connected"
        sys.stdout = saveout
        fsock.close()
    else:
        ivvinetwork = win32com.client.Dispatch('Wscript.Network')
        network_drives = ivvinetwork.EnumNetworkDrives()
        for mapped_drive in [network_drives.Item(i)
                             for i in range(0, network_drives.Count() -1 , 2)
                             if network_drives.Item(i)]:
            ivvinetwork.RemoveNetworkDrive(mapped_drive, True, True)
        drive_mapping = [
            ('z:', '\\\\192.168.1.100\\newmap', 'someuser', 'somepass')]
        for drive_letter, network_path, user_name, user_pass in drive_mapping:
            try:
                ivvinetwork.MapNetworkDrive(drive_letter, network_path, True, user_name, user_pass)
                saveout = sys.stdout
                fsock = open('status.log', 'a')
                sys.stdout = fsock
                print os.getenv("COMPUTERNAME"), " - ", time.ctime(), " - ", drive_mapping, "Drive Has Been Mapped"
                sys.stdout = saveout
                fsock.close()
            except Exception, err:
                saveout = sys.stdout
                fsock = open('status.log', 'a')
                sys.stdout = fsock
                print os.getenv("COMPUTERNAME"), " - ", time.ctime(), " - ", err
                sys.stdout = saveout
                fsock.close()

def checkOldDrive():
    if os.path.exists('z:'):
        ivvinetwork = win32com.client.Dispatch('Wscript.Network')
        network_drives = ivvinetwork.EnumNetworkDrives()
        for mapped_drive in [network_drives.Item(i)
                             for i in range(0, network_drives.Count() -1 , 2)
                             if network_drives.Item(i)]:
            ivvinetwork.RemoveNetworkDrive(mapped_drive, True, True)

checkOldDrive()
checkDrive()

我已经根据你所描述的脚本编写了一个脚本,我相信它完成了你所描述的

我试图用一种既符合Pythonic又遵循良好编程原则的方式来实现它

特别是,我做了以下工作:

  • 将大部分功能模块化为可重用的功能
  • 尽量避免重复。我没有考虑硬编码的“Z:”驱动器。我把它留给你做练习(你认为合适)
  • 将日志定义分解到一个位置(因此格式等是一致的,不会重复)。日志模块使这变得简单
  • 将所有代码移出顶级范围(某些全局常量除外)。这允许脚本直接运行或由另一个脚本作为模块导入
  • 添加了一些文档字符串,以帮助记录每个函数的功能
  • 使每个函数简洁明了,以便在单个屏幕和孤立的上下文中更容易阅读
当然,还有一些改进的余地,但是我已经测试了这个脚本,它是功能性的。它应该提供一些很好的教训,同时也帮助你完成任务。享受

#!/usr/bin/env python
import os
import time
import win32com.client
import logging

old_mappings = [
    r'\\192.168.1.100\old',
    ]
new_mapping = r'\\192.168.1.200\new'
LOG_FILENAME = 'status.log'

def main():
    """
    Check to see if Z: is mapped to the old server; if so remove it and
    map the Z: to the new server.

    Then, repeatedly monitor the Z: mapping. If the Z: drive exists,
    report to status.log that we are working. Otherwise, re-map it and
    report errors to the log.
    """
    setupLogging()
    replaceMapping()
    monitorMapping()

def replaceMapping():
    if removeMapping():
        createNewMapping()

def setupLogging():
    format = os.environ['COMPUTERNAME'] + " - %(asctime)s - %(message)s"
    logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG, format=format)

def getCredentials():
    """
    Return one of three things:
    - an empty tuple
    - a tuple containing just a username (if a password is not required)
    - a tuple containing username and password
    """
    return ('someuser', 'somepass')

def createNewMapping():
    network = win32com.client.Dispatch('WScript.Network')
    params = (
        'Z:', # drive letter
        new_mapping, # UNC path
        True, # update profile
        )
    params += getCredentials()
    try:
        network.MapNetworkDrive(*params)
        msg = '{params} - Drive has been mapped'
        logging.getLogger().info(msg.format(**vars()))
    except Exception as e:
        msg = 'error mapping {params}'
        logging.getLogger().exception(msg.format(**vars()))

def monitorMapping():
    while True:
        # only check once a minute
        time.sleep(60)
        checkMapping()

def checkMapping():
    if getDriveMappings()['Z:'] == new_mapping:
        msg = 'Drive is still mapped'
        logging.getLogger().info(msg.format(**vars()))
    else:
        replaceMapping()

# From Python 2.6.4 docs
from itertools import izip_longest
def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

def getDriveMappings():
    """
    Return a dictionary of drive letter to UNC paths as mapped on the
    system.
    """
    network = win32com.client.Dispatch('WScript.Network')
    # http://msdn.microsoft.com/en-us/library/t9zt39at%28VS.85%29.aspx
    drives = network.EnumNetworkDrives()
    # EnumNetworkDrives returns an even-length array of drive/unc pairs.
    # Use grouper to convert this to a dictionary.
    result = dict(grouper(2, drives))
    # Potentially several UNC paths will be connected but not assigned
    # to any drive letter. Since only the last will be in the
    # dictionary, remove it.
    if '' in result: del result['']
    return result

def getUNCForDrive(drive):
    """
    Get the UNC path for a mapped drive.
    Throws a KeyError if no mapping exists.
    """
    return getDriveMappings()[drive.upper()]

def removeMapping():
    """
    Remove the old drive mapping. If it is removed, or was not present,
    return True.
    Otherwise, return False or None.
    """
    mapped_drives = getDriveMappings()
    drive_letter = 'Z:'
    if not drive_letter in mapped_drives:
        return True
    if mapped_drives[drive_letter] in old_mappings:
        network = win32com.client.Dispatch('WScript.Network')
        force = True
        update_profile = True
        network.RemoveNetworkDrive(drive_letter, force, update_profile)
        return True
    # return None

if __name__ == '__main__':
    main()

我刚刚意识到使用成对排列有一个很大的错误。这不是正确的功能,它只在我的环境中工作,因为我只有一个驱动器号映射。我会很快修复并发布和编辑。感谢
getDriveMappings()
getUNCForDrive()
使用win32 api检索信息,这正是我从一段时间以来一直在搜索的内容…:-)