How do I write remote machine Path in askopenfilename - python

I am writing a program in python on Ubuntu, to remove a file from remote machine(raspberrypi) by accessing it, connected with network.
For file selection I am using a command called askopenfilename.
But I am struggling in specifying the Path of RaspberryPi correctly.
Can you please guide me on how do I specify Raspberrypi path correctly?
IP = "192.168.2.34"
Username = "pi"
Password ="raspberry"
Path="/home/pi/python"
Below is my code
from tkFileDialog import askopenfilename
import paramiko
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('192.168.2.34', username='pi', password='raspberry')
checkdir = "/home/pi/python"
name1= askopenfilename(title = "Select File For Removal", initialdir = checkdir)
stdin, stdout, stderr = client.exec_command('ls -l')
for line in stdout:
print '... ' + line.strip('\n')
client.close()

I am fairly sure the tk file dialog is only able to browse the Ubuntu machine (which it seems to run on) filesystem - not the RPi filesystem over SSH, so you will never see RPi directories.
if You can read the RPi directory listing there, so you could create your own file browser component or try to find an existing one that works over SSH.
Then again it looks like you are 'inventing the wheel again' (which of course is ok for learning purposes) - gFTP, FileZilla, many of the Linux desktop file browsers etc. (or WinSCP if you were using a Windows box) are ready made tools for this.

Related

Python os.mkdir still creates folders locally even after connecting to SSH server using Paramiko

The principle of the script is that it should connect from one virtual machine to another via an SSH connection and generate a certain number of folders.
The script runs, but when executed, generates folders on the host machine.
import os
from paramiko import SSHClient, AutoAddPolicy
from sys import argv
address = argv[1]
port = int(argv[2])
name = argv[3]
path = argv[4]
prefix = argv[5]
counts = int(argv[6])
mode = int(argv[7])
def generateFolders(path, prefix, counts, mode):
for i in range(1, counts+1):
folderName = prefix + str(i)
pth = os.path.join(os.path.expanduser('~'), path, folderName)
os.mkdir(pth, mode)
command = generateFolders(path, prefix, counts, mode)
print(address)
client1 = SSHClient()
client1.set_missing_host_key_policy(AutoAddPolicy())
client1.connect(address, username=name, password='1')
stdin, stdout, stderr = client1.exec_command(command)
print(stdout.read())
client1.close()
The command in the terminal
But without a script, I can connect to another virtual machine
Jane, its making dirs on your local box because that is where the python script is running.
I suggest you look at this question and answer.
In that QandA, they show how to use ssh on the local box to execute commands on a remote box. You could use your existing code as the code which is run on the remote box using the above as your guide.
Specifically this this one
The os.mkdir creates folders on the local machine. It won't magically start working on a remote machine only because you have previous opened SSH connection to that machine (and you actually even did not, as you open it only after calling os.mkdir).
To create a folder on a remote machine via Paramiko module, use SFTPClient.mkdir.
sftp = client1.open_sftp()
for i in range(1, counts+1):
folderName = prefix + str(i)
pth = os.path.join(os.path.expanduser('~'), path, folderName)
sftp.mkdir(pth, mode)
Though you should not use os.path on SFTP paths as your code will break, if run on Windows and other platforms, that does not use / as a path separator. And os.path.expanduser will of course expand ~ to local user home. I do not think you want that.
Obligatory warning: Do not use AutoAddPolicy on its own – You are losing a protection against MITM attacks by doing so. For a correct solution, see Paramiko "Unknown Server".

Copy file from local to remote desktop in Python using subprocess

I am trying to create a program for a project of mine where I needed to copy some files from my local machine to some remote desktop pc's desktop directory. It is a part of automating the whole connecting and copying files to all the remote PCs. I have used subprocess to connect to a remote desktop. As I am a beginner of using subprocess or cmd commands, I am unable to find a way to do this. This is the code:
from pynput.keyboard import Key,Controller
import time
import subprocess
def process_exists(process_name):
call = 'TASKLIST', '/FI', 'imagename eq %s' % process_name
output = subprocess.check_output(call)
last_line = output.decode("utf-8").strip().split('\r\n')[-1]
return last_line.lower().startswith(process_name.lower())
#os.system('cmd /k "mstsc /v:192.168.0.107"')
#os.system('cmd /c "notepad"')
from subprocess import Popen
p = Popen('mstsc /v:192.168.0.107')
time.sleep(1)
keyboard = Controller()
# Password is given here
for i in range(10):
if process_exists('mstsc.exe'):
time.sleep(1)
keyboard.type("**********")
keyboard.press(Key.enter)
time.sleep(0.12)
break
time.sleep(3)
Here I used subprocess just to connect to that remote PC. I tried
Popen(r'copy /Y "E:\test.jar" "\\192.168.0.107\c\"')
But it didn't help. Though I didn't know the basic of this line. The error it showed was:
FileNotFoundError: [WinError 2] The system cannot find the file specified
This code is only for test, that's why I used only time delay, didn't check whether it ran correctly.
The remote desktop started successfully. But unable to start the copying process.
Sorry for my bad English. Thanks in advance

Using WMI-Client-Wrapper to execute an exe and get output logs

Objective:
I am using Ubuntu 16.04 and am using WMI-CLient-Wrapper module to connect to a remote Windows Machine and send an executable to it(eg. Process Explorer) and further execute it and collect the logs it creates and fetch them back to my Linux Machine for further processing. Using WMI CLient Wrapper is the only option available as WMI Module doesn't work with Linux.
Problem:
I am able to send the file to the remote Windows machine, by establishing a connection using WMI-Client-Wrapper and SMB File Transfer Mechanism. After that when I try to create a Process for the same and try to execute that process it gives me an error stating that some of the attributes that WMI actually has, are not supported by WMI client Wrapper.
What I tried
Python Code:
import os
import wmi_client_wrapper as wmic
from socket import *
import time
wmic = wmic.WmiClientWrapper(
host ="192.168.115.128",
username = "LegalWrongDoer",
password = "sasuke14"
)
SW_SHOWNORMAL = 1
str = "smbclient //192.168.115.128/C$ -U LegalWrongDoer%sasuke14 -c \'put \"procexp64.exe\"\'"
os.system(str)
print("Folder sent")
process_startup = wmic.Win32_ProcessStartup.new()
process_startup.ShowWindow = SW_SHOWNORMAL
process_id, result = wmic.Win32_Process.Create(CommandLine="C:/procexp64.exe", ProcessStartupInformation=process_startup)
process_startup.ShowWindow = SW_SHOWNORMAL
if result == 0:
print("Process started successfully")
else:
print("Sorry, but can't execute Process!")
When I run this python file, it gives me the output to the initial query I make. But the Process_StartUp fails.
Further Traceback Calls:
Traceback (most recent call last):
File "WMIClient.py", line 22, in <module>
process_startup = wmic.Win32_ProcessStartup.new()
AttributeError: 'WmiClientWrapper' object has no attribute 'Win32_ProcessStartup'
I'd be extremely grateful if anyone of you can be able to help me through this. Thanks in advance :)
Well I finally managed to get a work-around for this whole scenario, and it might look a little messy but it sure does work for me.
Firstly I use smbclient to transfer the executable to the end-point where I want to execute it. Inside my code I use os.system() calls to make this happen.
import os
str1 = "smbclient //'<HostMachineIP>'/admin$ -U '<domain>\\<username>%<password>' -c \'lcd /usr/local/acpl/bin/endPoint/; put \"EndPointForeignsics.exe\"\'"
os.system(str1)
This helps me put the executable in desired shared folder that the user has access(Admin in my case) to and then use WMI-query through a tool called Winexe to get access to the console/command prompt of the end-point. I use another os.system() call to execute this again.
str2 = r'/usr/local/bin/winexe -U "<domain>\\<username>%<password>" //<HostMachineIP> "cmd /c c:\windows\EndPointForeignsics.exe '
os.system(str2)
P.S:-- Winexe is a tool that you'll have to download off the internet and compile it. It may take some time and effort to do that, but is quite achievable. You'll get a lot of help on the same from StackOverflow and Documentation of the tool.

Python-Application .desktop-shortcut causing malfunction

I wanted to create a desktop launcher for my Python application. The application executes various ssh operations over pexpect with publickey-authentication. The problem is however, when I start my app with the .desktop launcher it doesn't work properly. The ssh connections ask for a password and don't use the publickeys. But it works fine via commandline execution.
The .desktop File looks like this:
[Desktop Entry]
Version=1.0
Name=SSH-Manager
Comment=XYZ
Exec=python /home/userx/SSH-Manager/startup.py
Icon=/home/userx/SSH-Manager/resources/icon.png
Path=/home/userx/repos/SSH-Manager
Terminal=true
Type=Application
Categories=Utility;Application;
StartupNotify=false
The desktop environment is KDE and the desktop user is the same as the commandline user.
Can someone explain why I get such strange behavior with the launcher?
Edit: Example function
def run(self):
self.a_signal.emit("Retrieving Data")
try:
session = pxssh()
session.force_password = False
hostname = self.client
username = "root"
session.login(hostname, username)
session.sendline("ls -a")
session.prompt()
session.logout()
except ExceptionPxssh as e:
print ("pxssh failed: ")
self.error_signal.emit("failed", str(e))
print e
return
self.process_output()
self.finish_signal.emit("done")
As Mirosław Zalewski suspected in the comments, the problem was the ssh-agent was not running for the desktop-environment because ssh-add was initially used in the /etc/sources. Executing ssh-add in the X-users ~./profile therefore solves the problem.

os.walk works from console but not from cgi-bin

When I run this os.walk code from my PyScripter IDE, it works just fine. The os.walk was able to traverse the remote unix path and print the directory and file names.
However, when I run this same script from the cgi-bin of my Apache server, I get no os.walk (path, dirs, files) output. I also don't get any error messages recorded in the Apache error.log file.
Note: Python and my cgi-bin are on the same Windows machine, and the remote_path is on Unix.
Why does this same code work from the console but not from the cgi-bin and what can I do to resolve this?
#!C:\Python27\python.exe -u
import os
print "Content-type: text/html\n\n";
print "<html><head>"
print "<font size=+2><B>os.walk test</B></font><br><br>";
# Remote path
remote_path = r'\\unix_server\path\2015\q1\files\na\canada'
i = 0
for (path, dirs, files) in os.walk(remote_path):
print "Path", path
print "<BR><BR>Dirs", dirs
print "<BR><BR>Files", files
i += 1
if i >= 1:
break
Thanks to kindall, I found out the problem was indeed that Apache didn't have the appropriate permissions.
To solve the issue, I did the following (Windows 7 OS):
Opened services.msc. Start -> Run -> "services.msc"
Located my Apache service in the list "Apache2". Double click it.
In the Properties dialog for the Apache2 service, switch to the "Log On" tab. The radio button for "Local System account" was checked. I switched it to "This account" and clicked Browse.
In the "Enter object name to select" text box, I entered the name of my network + backslash + my user name. For example NETWORK\username. Clicked OK.
Then on the Log On tab, I saw that my full network email address was populated. I entered my password and password confirmation and clicked Apply.
The final steps were to stop the Apache2 service and then restart the service. Once that was done, the problem was solved and my script started working from the cgi-bin. :)

Categories