使用Python映射Windows驱动器的最佳方法是什么?
用Python把网络共享映射到Windows驱动器的最好方法是什么?这个共享还需要用户名和密码。
7 个回答
3
我在家没有服务器可以测试,但你可以试试用标准库里的子进程模块来执行合适的 NET USE 命令。
在 Windows 命令提示符下输入 NET HELP USE,可以看到你应该可以在 net use 命令中同时输入密码和用户名来映射驱动器。
下面是一个简单的测试,演示一个没有映射内容的 net use 命令:
>>> import subprocess
>>> subprocess.check_call(['net', 'use'])
New connections will be remembered.
There are no entries in the list.
0
>>>
13
好的,这里有另一种方法...
这个方法是在研究了win32wnet之后得出的。你觉得怎么样呢...
def mapDrive(drive, networkPath, user, password, force=0):
print networkPath
if (os.path.exists(drive)):
print drive, " Drive in use, trying to unmap..."
if force:
try:
win32wnet.WNetCancelConnection2(drive, 1, 1)
print drive, "successfully unmapped..."
except:
print drive, "Unmap failed, This might not be a network drive..."
return -1
else:
print "Non-forcing call. Will not unmap..."
return -1
else:
print drive, " drive is free..."
if (os.path.exists(networkPath)):
print networkPath, " is found..."
print "Trying to map ", networkPath, " on to ", drive, " ....."
try:
win32wnet.WNetAddConnection2(win32netcon.RESOURCETYPE_DISK, drive, networkPath, None, user, password)
except:
print "Unexpected error..."
return -1
print "Mapping successful"
return 1
else:
print "Network path unreachable..."
return -1
要取消映射,只需使用....
def unmapDrive(drive, force=0):
#Check if the drive is in use
if (os.path.exists(drive)):
print "drive in use, trying to unmap..."
if force == 0:
print "Executing un-forced call..."
try:
win32wnet.WNetCancelConnection2(drive, 1, force)
print drive, "successfully unmapped..."
return 1
except:
print "Unmap failed, try again..."
return -1
else:
print drive, " Drive is already free..."
return -1
32
基于@Anon的建议:
# Drive letter: M
# Shared drive path: \\shared\folder
# Username: user123
# Password: password
import subprocess
# Disconnect anything on M
subprocess.call(r'net use m: /del', shell=True)
# Connect to shared drive, use drive letter M
subprocess.call(r'net use m: \\shared\folder /user:user123 password', shell=True)
我更喜欢这种简单的方法,特别是当所有信息都是静态的,也就是不会改变的时候。