Was ist der beste Weg, um eine Netzwerkfreigabe zu einem Windows-Laufwerk mit Python zuordnen? Diese Freigabe erfordert auch einen Benutzernamen und ein Passwort.Was ist der beste Weg, Windows-Laufwerke mit Python zu mappen?
Antwort
Ich würde mit IronPython gehen und diesen Artikel: Mapping a Drive Letter Programmatically. Oder Sie können die Win32-API direkt verwenden.
Hier sind ein paar Links, die die Verwendung des win32net-Moduls zeigen, das die von Ihnen benötigte Funktionalität bereitstellen sollte.
http://docs.activestate.com/activepython/2.4/pywin32/html/win32/help/win32net.html http://www.blog.pythonlibrary.org/?p=20
Ich habe keinen Server mit hier zu Hause zu testen, aber vielleicht könnten Sie einfach die Standard-Bibliothek Subprozess Modul verwenden Sie den entsprechenden NET USE Befehl auszuführen?
Wenn Sie NET HELP USE von einer Windows-Eingabeaufforderung aus betrachten, sieht es so aus, als ob Sie das Kennwort und die Benutzer-ID im Befehl net use eingeben können, um das Laufwerk zuzuordnen.
Ein schneller Test im Interpreter eines bloßen Befehl net use w/o die Abbildung Material:
>>> import subprocess
>>> subprocess.check_call(['net', 'use'])
New connections will be remembered.
There are no entries in the list.
0
>>>
Unter der Annahme, dass Sie die notwendigen Bibliotheken importieren, das war ein Teil eines RPC-Server, auf dem der Client die angeforderten Server ein Laufwerk lokal zur Karte ...
#Small function to check the availability of network resource.
def isAvailable(path):
winCMD = 'IF EXIST ' + path + ' echo YES'
cmdOutPut = subprocess.Popen(winCMD, stdout=subprocess.PIPE, shell=True).communicate()
return string.find(str(cmdOutPut), 'YES',)
#Small function to check if the mention location is a directory
def isDirectory(path):
winCMD = 'dir ' + path + ' | FIND ".."'
cmdOutPut = subprocess.Popen(winCMD, stdout=subprocess.PIPE, shell=True).communicate()
return string.find(str(cmdOutPut), 'DIR',)
================ überprüfen sie die weißen Flächen von hier, das war ein Teil einer Funktion ==== ========
def mapNetworkDrive(self, drive, networkPath, user, password):
#Check for drive availability
if isAvailable(drive) > -1:
#Drive letter is already in use
return -1
#Check for network resource availability
if isAvailable(networkPath) == -1:
print "Path not accessible: ", networkPath
#Network path is not reachable
return -1
#Prepare 'NET USE' commands
winCMD1 = 'NET USE ' + drive + ' ' + networkPath
winCMD2 = winCMD1 + ' ' + password + ' /User' + user
print "winCMD1 = ", winCMD1
print "winCMD2 = ", winCMD2
#Execute 'NET USE' command with authentication
winCMD = winCMD2
cmdOutPut = subprocess.Popen(winCMD, stdout=subprocess.PIPE, shell=True).communicate()
print "Executed: ", winCMD
if string.find(str(cmdOutPut), 'successfully',) == -1:
print winCMD, " FAILED"
winCMD = winCMD1
#Execute 'NET USE' command without authentication, incase session already open
cmdOutPut = subprocess.Popen(winCMD, stdout=subprocess.PIPE, shell=True).communicate()
print "Executed: ", winCMD
if string.find(str(cmdOutPut), 'successfully',) == -1:
print winCMD, " FAILED"
return -1
#Mapped on second try
return 1
#Mapped with first try
return 1
def unmapNetworkDrive(self, drive):
#Check if the drive is in use
if isAvailable(drive) == -1:
#Drive is not in use
return -1
#Prepare 'NET USE' command
winCMD = 'net use ' + drive + ' /DELETE'
cmdOutPut = subprocess.Popen(winCMD, stdout=subprocess.PIPE, shell=True).communicate()
if string.find(str(cmdOutPut), 'successfully',) == -1:
#Could not UN-MAP, this might be a physical drive
return -1
#UN-MAP successful
return 1
Okay, hier ist eine andere Methode ...
Dieser war nach dem Durchlaufen von win32wnet. Lassen Sie mich wissen, was Sie denken ...
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
Und unmappen, nur verwenden ....
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
Gebäude off Vorschlag von @ 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)
Ich ziehe diese einfacher Ansatz, besonders wenn alle Informationen statisch sind.
Ich habe eine Frage zu diesem Setup. Wenn Sie versuchen, ein Laufwerk in einer Webanwendung zuzuordnen, wird das Laufwerk dem Benutzer zugeordnet, der die App oder den Server ausführt? – wolf97084
Verwenden Sie "net use a:/del/Y" zu erzwingen, sonst wird es auf Anfrage nach Bestätigung zu löschen – Tahlor
Auch wenn wir net verwenden * '+ "\\ UNC Pfad \ Ordner" wird automatisch eine leere finden Laufwerksschacht zum Mounten von "UNC \ Pfad \ Ordner" – Dylan
Ich hatte Probleme diese Linie den Weg zur Arbeit:
win32wnet.WNetAddConnection2 (win32netcon.RESOURCETYPE_DISK, Antrieb, NetworkPath, None, Benutzer, Passwort) mit dieser
Aber erfolgreich war:
win32wnet .WNetAddConnection2 (1, 'Z:', r '\ UNCpath \ share', keine, 'Login', 'password')
Wenn Sie den aktuellen Login-Benutzer zuordnen möchten, denke ich Subprozess Ihr Problem zu lösen. Aber möchten Sie verschiedene Zuordnungen für verschiedene Benutzer von einem einzigen Hauptkonto aus steuern? Sie könnten dies aus dem Register der Windows
Die Idee besteht darin, das Profil eines bestimmten Benutzers zu laden.
import win32api
import win32security
import win32profile
import win32netcon
import win32net
import win32netcon
import win32con
il = 'G'
m = '\\\\192.168.1.16\\my_share_folder'
usu = 'my_user'
cla = 'passwd'
#login the user
hUser = win32security.LogonUser(
usu,
None,
cla,
win32security.LOGON32_LOGON_NETWORK,
win32security.LOGON32_PROVIDER_DEFAULT
)
#load the profile
hReg = win32profile.LoadUserProfile (
hUser,
{"UserName" : usu}
)
#alter the regedit entries of usu
win32api.RegCreateKey(hReg, "Network")
hkey = win32api.RegOpenKey(hReg, "Network\\", 0, win32con.KEY_ALL_ACCESS)
win32api.RegCreateKey(hkey, il)
hkey = win32api.RegOpenKey(hReg, "Network\\%s" % il, 0, win32con.KEY_ALL_ACCESS)
win32api.RegSetValueEx(hkey, "ConnectionType", 0, win32con.REG_DWORD, 1)
win32api.RegSetValueEx(hkey, "DeferFlags", 0, win32con.REG_DWORD, 4)
win32api.RegSetValueEx(hkey, "ProviderName", 0, win32con.REG_SZ, "Red de Microsoft Windows")
win32api.RegSetValueEx(hkey, "ProviderType", 0, win32con.REG_DWORD, 131072)
win32api.RegSetValueEx(hkey, "RemotePath", 0, win32con.REG_SZ, m)
win32api.RegSetValueEx(hkey, "UserName", 0, win32con.REG_DWORD, 0)
Die Verwendung von 'win32wnet.WNetAddConnection2' und' win32wnet.WNetCancelConnection2' ist eine gute Idee. Aber das Abfangen von Ausnahmen und das Zurückgeben eines Rückkehrcodes scheint unnötig. Die integrierten Ausnahmen bieten Ihnen bereits gute Rücksende-Informationen. Es ist auch nicht gut, ein leeres 'except' zu fangen. – twasbrillig