download/upload files to remote windows server using python - python

I want to download/upload file from remote windows 2008 R2 servers using my python script. The problem is I do not want to install anything extra on my windows server box. I want to achieve this just using my normal login credentials.
Below are the different methods I heard of:
Use paramiko SSH : But to use this we have to install an SSH service on the remote box, which i do not want to do.
Use python wmi module: But I guess it does not have the functionality to download files from the remote servers.
Mount drives on your local box: Also do not want to do this as there will be lot of machines i want to connect to.
Use winscp: I guess it will also require SSH ?
Fabric: Heard of this, not sure what are its prerequisites.
are there any other methods with which i can achieve this?

When in windows do as the windows-users do.
If you can't install additional software on the server, you need to mount the drive, and interact with the remote files like they are local files.
You mention that you have too many remote servers to connect to. Why not pick one drive letter, and reuse it for each server you need to connect to?
With net use you can mount from the command line.
Syntax for net use
net use p: /delete:yes
net use p: \\remote_host\share_name password /user:domain\user
Use Python's subprocess package to run the mount commands. Subprocess tutor.
import subprocess
# Make sure the drive isn't mounted.
try:
subprocess.call('net use p: /delete:yes', shell=True)
except:
# This might fail if the drive wasn't in use.
# As long as the next net use works, we're good.
pass
for host in ("host1", "host2"):
# mount(map) the remote share.
subprocess.call('net use p: \\%s\share_name password /user:domain\user' % host, shell=True)
with open("p:\path\remote-file.txt", "r") as remote_file:
# do stuff
# dismount(map) the drive
subprocess.call('net use p: /delete:yes', shell=True)
(Don't have a windows box and network to test this on.)

Use the win_unc library: http://covenanteyes.github.io/py_win_unc/
This will allow you to do normal modifications to file paths as well as log in as a different user.

Related

Copy folder from server(Linux) to local machine(windows) in python

How to copy a folder from Server (linux) to a local machine (windows) in python.
I tried with the given code but it did not work
from distutils.dir_util import copy_tree
copy_tree("source_path ","destination_path")
I used copy_tree command to copy a folder on my local machine but when I used the same command to copy a folder from server to local machine then it did not work.
Any other method is there? Or any changes needed?
You need to use SSH, SCP, or SFTP to transfer files from host to host.
I do this a lot and like to use SSH and SCP. You can run and SSH server on your windows machine using OpenSSH. Here is a good set of instructions from WinSCP: https://winscp.net/eng/docs/guide_windows_openssh_server.
I recommend using Paramiko for SSH with Python. Here is a good answer showing how this works with python: https://stackoverflow.com/a/38556344/634627.
If you set up OpenSSH, you could also do this with SFTP, sometimes I find this is more suitable that SCP. Here is a good answer showing how that works: https://stackoverflow.com/a/33752662/634627
The trick is getting OpenSSH running on your Windows host and setting up SSH keys so your server can authenticate to your localhost.
Using copytree should work if:
the folder on the server is made available to the windows machine as a client.
you have sufficient access permissions.
you use a raw string for the windows path to prevent string interpretation.
Ad 3: try print('c:\test\robot'):
In [1]: print('c:\test\robot')
obot est

Execute command on remote windows machine and get output in python

I want to write a script that executes command on remote windows machine, and get output from that command. The problem is, I want to use built-in software in windows, so I can't unfortunately use for example SSH for that. I found "wmi" library, and I can log in to the machine and execute command, but i don't know how to recieve output from that command.
import wmi
c = wmi.WMI("10.0.0.2", user="administrator", password="admin")
process_startup = c.Win32_ProcessStartup.new()
process_id, result = c.Win32_Process.Create (r'cmd /c ping 10.0.0.1 -n 1 > c:\temp\temp.txt')
if result == 0:
print("Process started successfully: %d" % process_id)
print(result)
I tried to redirect output to file, but I can't find any way to get text file content either.
Is there any possible way to get output or text file content using wmi, or other python libraries?
For the application you're describing you may find RPyC is a good fit. It's a python remoting server you can connect to and issue commands; it will do anything that Python can do on the target machine. So you could, for example, use the subprocess module to run a windows command and capture the output then return the result.
The safe thing to do is to expose your remote functionality as a service -- basically, it's just a python script that RPyC can run for you. However you can also use RPyC classic mode, which is pretty much like running a python session directly on the remote machine. You should use it only when you are not worried about security, since classic mode can do anything on the remote machine -- but it's useful for prototyping.

Python to perform SSH logins and do something

I am trying to automate few routine tasks in Netapp storage using Python.
Since I am using Windows machine and Python I need to perform few tasks to connect storage using ssh session and perfom few things and I need view how it is acting . For example if we take we are connecting Linux box over ssh if I execute ls command I need to see the output of the ls.
To achieve this which tools I need to use ..I searched in web some are suggesting to use paramiko and pexpect but these are the modules to use connect ssh and perform tasks but we cannot view the output on terminal.
With the parallel-ssh library:
from pssh import ParallelSSHClient
# See also private key examples in documentation
client = ParallelSSHClient(['netapp.host'], user=<user>,
password=<password>)
output = client.run_command(<cmd>)
for line in output['netapp.host'].stdout:
print line
See parallel-ssh documentation. It uses paramiko under the hood so should work just as well on Windows.
stdin channel is also available in output for providing input like with pexpect, see run_command documentation for examples.
As a bonus, the client is parallel and can be used to run commands on any number of hosts.
Using paramiko directly is of course also possible, though a lot more code would be required which parallel-ssh does for you.

Python os.walk on a different computer on the same network

I would like to do an os.walk in python 2.7 in windows 7 but on a computer that is on the same network. Something like os.walk('\192.168.0.2') but this doesn't work. Is this possible?
Try net use or a UNC path.
Or try Linux, you'd probably be better off with it than Windows.
http://pcsupport.about.com/od/commandlinereference/p/net-use-command.htm
http://www.uwplatt.edu/oit/terms/uncpath.html
In python, using Windows paths is often easier if you use, for example, r'\\hostname\share' rather than '\\\\hostname\\share'.
My thought is also to go for Linux, or at least, Windows with SSH service.
Set up public key authentication over SSH, and make sure you can ssh to that Windows machine (with SSH service on, of course) without password and password phrase.
Make use of Fabric, a Python (2.5 or higher) library and command-line tool for streamlining the use of SSH for application deployment or systems administration tasks.
For Windows, what I did was opened File Explorer, and navigated to the (sub)folder of interest on the network drive, and right clicked on Properties. Copy the Location information, and paste that into your Python file.
Ex.
for root, dirs, files in os.walk("//<network name>/<folder>/<sub-folder1>/<sub-folder2>/.../<sub-folderN>"):
for file in files:
print(file)

How do I access a remote filesystem using Python on Windows?

I'm writing a Python script to access all computers on the network, log in to them and read some log files. I don't want to use something as low-level as socket, but I can if I must. I realize that my problem is similar to this question, but not the same.
Are there any modules for accessing external Windows machines?
Has anyone done anything like this before?
I'm specifically looking to log into Windows 7 machines, not unix.
Let's also assume that each computer I want to log into has Remote Desktop installed and enabled. I'm also not worried about network security or encryption because these files are not confidential. Windows machines don't have SSH installed on the by default do they?
There has to be something on the other side for you to talk to. This limits you to either setting up a "server" on each machine, installing a real server (i.e. sshd), building a "server" yourself and installing it, or using a built in and active feature of the OS.
Based upon this, what kind of system do you want to set up on these machines? What does it need to do? Just read the contents of a prespecified file list? Will that list change?
One solution is to turn on telnet, and use paramiko or twisted to
talk across it. This isn't very secure of course
Next up, set up a samba share, and access the folder remotely. This
is also insecure, though less so than telnet
You could find a ssh daemon port and run that, if you are so inclined
Psexec from sysinternals might work
Use twisted to build a server app with the features you need
Use ncat to listen on a port and spawn a cmd prompt
Be aware that most of the solutions for accessing windows remotely are... poor. The best solution is probably to roll your own, but that is hard work and you will probably make mistakes.
Also, Windows 7 is not exactly multi-user friendly. Individual processes can run as separate users, but the OS does not support having multiple users logged in at the same time. Someone is going to be the "user" and everyone else is just a process with a different credential set.
This is more an artificial limitation on M$'s part than anything technical. To see this in action, try to log in with RDP while a user is logged in locally. Fun times.
Per your edit, the easiest thing to do is just set up a samba share on the box.
After this share is set up:
with open(r'\\myCompNameOrIP\C\windows\logs\logfile.txt','rb') as logfile:
loglines = logfile.readlines()
Or you can use the gencat sample found here. Just give it r'\\myCompNameOrIP\C\windows\logs\*.txt' as the search path and watch the magic.
From Ubuntu I use samba:
In Bash:
gvfs-mount smb://them/folder
Here I give name, domain and password
Then in python:
folder = '/home/me/.gvfs/folder on them'
using the os module I read folders and files inside.
I am working in a small business environment.
Why not have each of the computers send the log file to the central computer?

Categories