Hello,
I’ve just started learning Python.
We have an important file that sites on our Windows machines that sit in remote factories. I need to pull this modified date from each machine and wonder if Python can do that? These machines are not domain’d, but I have a local username and password to get remote access.
I’d like the output to be in csv for starters. So poll time, IP/Hostname, Modified Date.
I did find this script and wonder what you thought?
import os
import socket
import ctypes
from ctypes import wintypes
def get_unc_credentials(remote_path):
# Get the username and password for the UNC path
username = input("Enter the username: ")
password = input("Enter the password: ")
return username, password
def remote_check_modified_date(remote_path):
try:
# Check if the path is a UNC path (starts with \\)
if remote_path.startswith('\\\\'):
# Split the UNC path into server and share
server, share, path = remote_path[2:].split('\\', 2)
# Check if the server is reachable
if socket.gethostbyname(server):
# Construct the full UNC path
full_unc_path = f'\\\\{server}\\{share}\\{path}'
# Get credentials for the UNC path
username, password = get_unc_credentials(full_unc_path)
# Use the Windows API to authenticate with the remote server
net_use_info = wintypes.NETRESOURCE()
net_use_info.lpRemoteName = full_unc_path
net_use_info.dwType = 0
net_use_info.lpLocalName = None
net_use_info.lpProvider = None
result = ctypes.windll.mpr.WNetAddConnection2W(
ctypes.byref(net_use_info),
password.encode('utf-16le'),
username.encode('utf-16le'),
0
)
if result == 0: # Success
# Get the file information
file_stat = os.stat(full_unc_path)
# Get the modified time from the file information
modified_time = file_stat.st_mtime
print(f"Modified date of {remote_path}: {modified_time}")
# Disconnect from the remote server
ctypes.windll.mpr.WNetCancelConnection2W(full_unc_path, 0, 1)
else:
print(f"Error: Unable to connect to {full_unc_path}, error code: {result}")
else:
print(f"Error: Server {server} not reachable")
else:
print("Error: Not a valid UNC path")
except Exception as e:
print(f"Error: {e}")
# Example usage
remote_check_modified_date('\\\\remote_host\\share\\path\\to\\file.txt')
I’m yet to test this until I’m onsite and will need a way to look at a list of multiple IP/Hostnames and send to csv. Getting just 1 remote IP working would be great though.
Thanks