I work with python 2.7 and I have a python script that ssh to remote servers and it works fine using python command from cmd but when I convert this script to executable file using py2exe or cx_freeze or Pyinstaller and try to run it, the window open and close immediately like if the program crashes. I tried another simple scripts like print function or some math function the executable files work fine so any one could help what would be the reason?
Thanks
Here is my code:
import sys
import paramiko
import getpass
def print_menu():
print 30 * "-", "MENU", 30 * "-"
print "1. LAB1"
print "2. LAB2"
print "3. LAB3"
print "4. Exit"
print 67 * "-"
def ssh_command(ssh):
while True:
command = raw_input("Enter command or q :")
ssh.invoke_shell()
stdin, stdout, stderr = ssh.exec_command(command)
stdout = stdout.readlines()
if command == "q":
break
for line in stdout:
if "Size" in line:
print "found the string"
break`enter code here`
else:
print "There was no output for this command"
def ssh_connect(host, user, password):
try:
ssh = paramiko.SSHClient()
print('Connecting...')
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=host, username=user, password=password)
ssh_command(ssh)
except Exception as e:
print('Connection Failed')
print(e)
def ssh_close():
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.close()
def credentials(host):
user = raw_input("Username:")
password = getpass.getpass("password for " + user + ":")
ssh_connect(host, user, password)
loop = True
while loop:
print_menu()
choice = input("Enter your choice [1-3]: ")
if choice == 1:
credentials('x.x.x.x')
elif choice == 2:
credentials('x.x.x.x')
elif choice == 3:
credentials('x.x.x.x')
elif choice == 4:
loop = False
print "Closing SSH connection"
print
ssh_close()
else:
raw_input("Wrong option selection. Enter any key to try again..")
You can check the error by running the exe file in command prompt.
This will give you an upper hand.
Especially in cx_freeze you have to mention the dependencies.
I think you are facing some dependency problem.
When you specifiy --debug=all after your pyinstall command when packaging, you will see specific errors when starting your applicataion in the dist folder.
Read here https://pyinstaller.readthedocs.io/en/stable/when-things-go-wrong.html to get more information on debugging specific errors and how to fix them.
you can use the pyinstaller with -F argument to fully package the python interpreter then open windows cmd and run it
pyinstaller -F <your_script>.py
Worry not, my friend! Just add a window.mainloop() call at the end of your program. Then, everything should work properly. I was stumped by the same problem got revelation from your words:
I tried another simple scripts like print function or some math function the executable files work fine
So, I compared both programs side by side and received my answer.
Running pyinstaller with the F flag should solve the problem of immediate close after startup.
Related
The idea to revoke users from the VPN, with an easyrsa command. Manually this works. However, when I perform this action with Python it fails.
The easyrsa command asks for 2 arguments, the first one is to continue, the second one is a password.
My current code is:
#!/usr/local/bin/python2.7
import time
from subprocess import Popen, PIPE
pass_phrase = "damn_good_password"
proc = Popen(['/usr/local/share/easy-rsa/easyrsa', 'revoke', 'user#somewhere.com'], stdin=PIPE)
time.sleep(1)
proc.stdin.write('yes\n')
proc.stdin.flush()
time.sleep(1)
proc.stdin.write(pass_phrase + "\n")
proc.stdin.flush()
The script outputs the following:
user#vpn $ sudo ./test.py
Type the word 'yes' to continue, or any other input to abort.
Continue with revocation: Using configuration from /usr/local/share/easy-rsa/openssl-1.0.cnf
Enter pass phrase for /etc/openvpn/pki/private/ca.key:
user#vpn $
User interface error
unable to load CA private key
5283368706004:error:0907B068:PEM routines:PEM_READ_BIO_PRIVATEKEY:bad password read:pem_pkey.c:117:
I think Python incorrectly passes the password to the process. When performing these steps manually and copying the password, it works.
Can someone point me in the right direction to fix this?
I'm new to python and i'm trying to make a password manager.
the problem is that my program works fine when i run it through IDLE or Pycharm
but it stops running when i run it directly from windows when it reaches the line where I import the file where i store the password.
import time
user = raw_input("Username: ")
pw = raw_input("Password: ")
if user == "PrOoOg" and pw == "aka443":
def add_acc_func(acc, user, pw):
database.write("\nAccount: ")
database.write(acc)
database.write(" Username: ")
database.write(user)
database.write(" Password: ")
database.write(pw)
database.close()
def print_database_func():
for lines in database.readlines():
print lines.strip('\n')
database.close()
user_input = raw_input('Press "A" to add a new account\nPress "M" to modify and existing account\n'
'Press "D" to delete and existing account\nPress "S" to show all accounts and passwords\n')
user_choice = user_input.lower()
if user_choice == "a":
database = open("source.txt", "a") #Everything worked fine when i deleted this line
acc_to_add = raw_input("Write the name of the site or service: ").lower()
acc_to_add_user = raw_input("Write the username or email you want to set for that account: ")
acc_to_add_pw = raw_input("Write the password you want to set to that account: ")
add_acc_func(acc_to_add, acc_to_add_user, acc_to_add_pw)
print "Account added"
if user_choice == "s":
database = open("source.txt", "r") #Everything worked fine when i deleted this line
print_database_func()
raw_input("Press Enter to quit")
else:
print ("Wrong username or password")
time.sleep(3)
I tried to delete the lines where I import the text file and it worked.
i don't know why the code can't open the file when opened from windows and can open it when opened from IDLE or Pycharm
"it's just crashes when i run it from windows (rightclick ==> open with ==> python.exe)"
When you do this the working directory is C:\Windows\system32. Most likely you don't have write permissions to this directory. When running the script using the other methods the working directory is most likely the one containing the script. You need to change to a directory which you have write permissions for.
Here is an example to use the current user's Documents folder:
import os
dir = os.path.expanduser('~/Documents')
os.chdir(dir)
It's my first week with python, so i would like to apologize in advance if my question sounds stupid.
Basically I wrote this code:
__author__ = 'houssam'
import subprocess
from subprocess import Popen, PIPE
check = subprocess.Popen(["winexe", "--system", "-U","mydomain\\myusername%mypassword", "//computername", "cmd /C c:\\Windows\\System32\\inetsrv\\appcmd list site"],stderr=subprocess.PIPE, stdout=subprocess.PIPE)
(stdout,stderr) = check.communicate()
if check.returncode == 0:
print 'IIS is installed on this system in the location below:'
print stdout
elif check.returncode == 1:
print 'IIS is NOT installed on this system ' and stderr
So basically I can query an IIS of a specific computer "//computername" and it works.
However i have 20 computers. I want to create a list list = [computer1,computer2,computer3] and then have a function that does: for each c in list replace the name of the computer into that only unique parameter "//computername" inside the subprocess.check_output that calls the winexe command so i don't have to write the command for all the computers I have.
I appreciate your help and suggestions.
Thank you,
Houssam
I actually found the answer:
I created a list of servers
servers = [//computer1", "//computer2"]
then I added a for statement and put the list inside the popen as follow:
for server in servers:
check= subprocess.Popen(["winexe", "--system", "-
U","mydomain\\myusername%mypassword",
server, "cmd /C c:\\Windows\\System32\\inetsrv\\appcmd list
site"],stderr=subprocess.PIPE,
stdout=subprocess.PIPE)
(stdout,stderr) = check.communicate()
if check.returncode == 0:
print 'IIS is installed on this system in the location below:'
print stdout
elif check.returncode == 1:
print 'IIS is NOT installed on this system ' and stderr
Then I put it in a function as follow:
def iis_check(servers):
for server in servers:
check= subprocess.Popen(["winexe", "--system", "-
U","mydomain\\myusername%mypassword",
server, "cmd /C c:\\Windows\\System32\\inetsrv\\appcmd list
site"],stderr=subprocess.PIPE,
stdout=subprocess.PIPE)
(stdout,stderr) = check.communicate()
if check.returncode == 0:
print 'IIS is installed on this system in the location below:'
print stdout
elif check.returncode == 1:
print 'IIS is NOT installed on this system ' and stderr
I am able to open a ssh session into switch using paramiko. Able to enter the commands and gets it respective output.
My question is that I want to enter many command into the switch simultaneously. But before entering new command, wanted to know that previous command is successfully entered into the switch.For example
switch>enable
switch#
switch#config t
switch(config)
Enter the 2nd command, until i see # sign and 3rd command untill i see config.
Following is the code i am using
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('ip-address',username='username', password='password')
list =['enable','config t']
command = '\n'.join(list)
#for i in range(len(list)):
print command
stdin,stdout,stderr = ssh.exec_command(command)
print(stdout.read())
use interactive invoke shell
##invoke interactive shell chan = ssh.invoke_shell(); chan.send(command + '\n') ;
while not chan.recv_ready(): print 'waiting for challenge' time.sleep(1) ;
resp = chan.recv(1024) ; print resp
i am trying to delete a directory but when i run the code it gives windows error 5: access is denied. here is my code: in the Release folder, there is a folder called OD.
if os.path.exists(os.path.join(get_path_for_output,'Release')):
shutil.rmtree(os.path.join(get_path_for_output,'Release'))
the error is like:
WindowsError: [Error 5] Access is denied: 'C:\\Users\\marahama\\Desktop\\Abdur_Release\\Release\\OD\\automations\\GEM\\FMS_adapter.py'
This was due to the file permissions issue.
You need to have the permissions to perform that task on that file.
To get the permissions associated with a file, useos.stat(fileName)
You can explicitly check the write permission for that file using os.access(fileName, os.W_OK)
Then, to change the permission, os.chmod(fileName,permissionNumeric).
Ex: os.chmod(fileName, '0777')
To change the permission for the current file that is being executed,
use os.chmod(__file__, '0777')
I use pydev. And my solution is:
Stop Eclipse.
Start Eclipse with option Run as administrator
takeown /F C:\<dir> /R /A
icacls C:\<dir> /grant administrators:F /t
Give ownership to administrators and give full control to administrators, if your user is an administrator.
in order to change files located in "C:" you must have admin privileges,
you can either get them before starting the script or while doing so, for instance:
#!python
# coding: utf-8
import sys
import ctypes
def run_as_admin(argv=None, debug=False):
shell32 = ctypes.windll.shell32
if argv is None and shell32.IsUserAnAdmin():
return True
if argv is None:
argv = sys.argv
if hasattr(sys, '_MEIPASS'):
# Support pyinstaller wrapped program.
arguments = map(unicode, argv[1:])
else:
arguments = map(unicode, argv)
argument_line = u' '.join(arguments)
executable = unicode(sys.executable)
if debug:
print 'Command line: ', executable, argument_line
ret = shell32.ShellExecuteW(None, u"runas", executable, argument_line, None, 1)
if int(ret) <= 32:
return False
return None
if __name__ == '__main__':
ret = run_as_admin()
if ret is True:
print 'I have admin privilege.'
raw_input('Press ENTER to exit.')
elif ret is None:
print 'I am elevating to admin privilege.'
raw_input('Press ENTER to exit.')
else:
print 'Error(ret=%d): cannot elevate privilege.' % (ret, )
code taken from: How to run python script with elevated privilege on windows
script by: Gary Lee