Windows CMD not seeing pip module paramiko - python

I'm writing a small script in Python, as a part of my networking class homework.
I have to run this script in cmd.exe, but it keeps giving me error ModuleNotFoundError: No module named 'paramiko'. It only works in IDLE, and only in 3.10 version.
File "C:\Users\drafthard\Documents\routerconfigscript4.py", line 1, in <module>
import paramiko
ModuleNotFoundError: No module named 'paramiko'
I've tried reinstalling paramiko, reinstalling pip, clearing pip cache and
installing paramiko again, showing path to paramiko files but nothing works.
Any idea how to solve this problem?
import paramiko
import time
user = 'user1'
pass1 = '12345'
port = 22
cisco = ['172.16.0.1', '172.16.0.2']
for host in cisco:
print('------Start---'+host+'------')
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname=host, username=user, password=pass1, port=port)
chan = client.invoke_shell()
time.sleep(2)
chan.send('terminal length 0\n')
time.sleep(1)
chan.send('show run\n')
time.sleep(1)
result = chan.recv(5000).decode('utf-8')
filename= str(host)+'.txt'
file=open(filename, 'w')
file.write(result)
file.close()
print(result)
time.sleep(2)
client.close()
print('------End-----'+host+'------')

Issue was solved by converting .py file to .exe with auto-py-to-exe and specifiying paramiko module in advanced settings.

Related

"Error 1053: The service did not respond timely", could not start Windows service created with cx_Freeze from Python code

I'm trying to create Windows service from my Python code using cx_Freeze. Python code works fine, it's debugged and reliable, but when I create exe file I got problems.
Here is my cx_Freeze setup code:
# Config file for packing python scripts into exe file
# Run with "python.exe create_win_exe.py build"
import sys
from cx_Freeze import setup, Executable
version = '1.00'
# Dependencies are automatically detected, but it might need fine tuning.
build_exe_options = {'packages': ['win32timezone'], 'includes': ['idna.idnadata']}
# Use default base - console application
base = None
setup(name = "service-test",
version = version,
description = "Service test",
options = {"build_exe": build_exe_options},
executables = [Executable("service-test.py", base=base)])
Python code (I've taken example from here How do you run a Python script as a service in Windows?):
# -*- coding: utf-8 -*-
import win32serviceutil
import win32service
import win32event
import servicemanager
import socket
import datetime
import time
class AppServerSvc (win32serviceutil.ServiceFramework):
_svc_name_ = "TestService5"
_svc_display_name_ = "Test Service 5"
stop_flag = False
def __init__(self,args):
win32serviceutil.ServiceFramework.__init__(self,args)
self.hWaitStop = win32event.CreateEvent(None,0,0,None)
socket.setdefaulttimeout(60)
def SvcStop(self):
self.stop_flag = True
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
win32event.SetEvent(self.hWaitStop)
def SvcDoRun(self):
servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
servicemanager.PYS_SERVICE_STARTED,
(self._svc_name_,''))
self.main()
def main(self):
fout = open('C:\\Users\\Константин\\service-test.log', 'w')
while not self.stop_flag:
try:
fout.write(str(datetime.datetime.now()) + '\n')
fout.flush()
except BaseException as be:
print('Error while writing to file: {}'.format(str(be)))
time.sleep(1)
if __name__ == '__main__':
win32serviceutil.HandleCommandLine(AppServerSvc)
When I create exe file, I could install it as service:
> service-test.exe install
Installing service TestService5
Service installed
Also I could finely debug it, it works as expected.
But it doesn't start:
> service-test.exe start
Starting service TestService5
Error starting service: The service did not respond timely
Same trouble if I use pyinstaller instead of cx_Freeze.
Could anybody help with it?
Might be permissions issue.
Looking at your code, you do not specify the account the service will be run under, so it is created under "Local System".
https://learn.microsoft.com/en-us/windows/desktop/Services/localsystem-account
Try indicating the user to run your service via the install command line arguments, or you can navigate to the services dialog (services.msc) after you've installed the service and modify the Log On.
I created a folder and placed two files into it: file.py and create_win_exe.py (file names not very important)
And I used the following command: pyinstaller file.py in that same directory and it ran through the install process fine. Once it was finished, I navigated into the dist/file/ directory and opened file.exe, and it worked perfectly fine. I'm not sure why you have an error, but try using pyinstaller exactly how I've shown and see if it works.

PyX not installed correctly when using scapy

I am trying to use scapy in python 3.6 to parse pcap files, and of the features I am trying to use is pdfdump.
from scapy.all import *
packets = rdpcap('***path***/nitroba.pcap')
for packet in packets[0:1]:
packet.psdump("isakmp_pkt.eps",layer_shift=1)
And I am getting the following error:
"ImportError: PyX and its depedencies must be installed"
Obviously I installed it, and a simple "import pyx" works, but the error persists. I did some digging and found that the problem originates in this code:
def _test_pyx():
"""Returns if PyX is correctly installed or not"""
try:
with open(os.devnull, 'wb') as devnull:
r = subprocess.check_call(["pdflatex", "--version"], stdout=devnull, stderr=subprocess.STDOUT)
except:
return False
else:
return r == 0
when executed, it determines if pyx is installed correctly, but it says "FileNotFoundError: [WinError 2] The system cannot find the file specified".
Ideas?
In my case (Ubuntu 18, scapy 2.4.3), I had to install pdflatex, i.e.,
sudo apt install texlive-latex-base
Got the answer myself - when I entered the scapy command line interface it said that I needed to install miktex which is a dependency of PyX, so I did.
The second error simply looks like a bug - it looks like there is a missing "import os" statement in the packet.py module, but there is an os.startfile in line 531.
I added it, and it worked:)
Its currently 2022 in the future and this works for me with Jupyer labs running on Ubuntu 20.04
pip install pyx
At least this works for me:
from scapy.all import *
pkt = IP()
pkt.canvas_dump()

Error executing Python script file through Talend tSystem

I have a .py file that i am trying to execute through Talend using tSystem module. I am getting below error.
Starting job MyJob at 07:06 20/02/2017.
[statistics] connecting to socket on port 3364
[statistics] connected
Traceback (most recent call last):
File "H:\Talend POC\NameParsingUSData.py", line 7, in <module>
from unidecode import unidecode
ImportError: No module named 'unidecode'
[statistics] disconnected
Job MyJob ended at 07:06 20/02/2017. [exit code=0]
This is how the job looks like.
Its strange, because when i double click the .py file, it executes and gives the result successfully. I also tried executing the file through cmd command line in command prompt, outside talend and it runs successfully as well. Not sure what might be causing the error. For reference below is my Python script.
import os
from unidecode import unidecode
import pandas as pd
dat = pd.read_csv("H:\\Talend POC\\1M_dummyData.csv")
df1.myvar = df1.myvar.str.replace(r"[^a-zA-Z., ]",r' ')
df1.myvar = df1.myvar.str.replace('\s+', ' ')
df1.myvar = df1.myvar.str.lstrip(".,' ")
df=df1.as_matrix()
df1.to_csv("H:\\Talend POC\\results_USvalidemail_parse.csv",header=True,index=False, encoding='utf-8')
Note that it successfully imports the first library, error starts from the second library import 'unicode'
Any help?
I don't know the reason why it works, but this is what my hack was. I searched for any .py file that exists in the Talend data integration dump and i found only one in the directory
C:\Users\user\Downloads\TOS_DI-20161216_1026-V6.3.1\plugins\org.apache.ant_1.9.2.v201404171502\bin
I tried installing the library in this directory in the command line.
Firstly i ran the below code in command line to go to the directory.
cd /d C:\Users\user\Downloads\TOS_DI-20161216_1026-V6.3.1\plugins\org.apache.ant_1.9.2.v201404171502\bin
Secondly, i installed the unidecode library using command pip install unidecode
I re-executed the talend job and it executed with success!!
tarting job MyJob at 08:05 20/02/2017.
[statistics] connecting to socket on port 3983
[statistics] connected
[statistics] disconnected
Job MyJob ended at 08:05 20/02/2017. [exit code=0]

ImportError: No module named paramiko

I have installed "python-paramiko" and "python-pycrypto" in Red hat linux.
But still when i run the sample program i get "ImportError: No module named paramiko".
I checked the installed packages using below command and got confirmed.
ncmdvstk:~/pdem $ rpm -qa | grep python-p
python-paramiko-1.7.6-1.el3.rf
python-pycrypto-2.3-1.el3.pp
My sample program which give the import error:
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(
paramiko.AutoAddPolicy())
ssh.connect('127.0.0.1', username='admin',
password='admin')
Actually all these packages were installed outside the python folder.
And all I did was linking the packages from python folder to packages folder.
It worked perfectly.

Python ldap AttributeError

I have an python error AttributeError: 'module' object has no attribute 'initialize'
I am running Python 2.6.2 on Solaris 10 UNIX and recently installed the pythonldap 2.3.9. The script is very basic, only has these 2 lines. Can anyone tell me why?? Traceback error below.
#!/usr/local/bin/python
import ldap, sys
con = ldap.initialize('ldap://localhost')
Traceback (most recent call last):
File "./myldap.py", line 5, in
con = ldap.initialize('ldap://localhost')
AttributeError: 'module' object has no attribute 'initialize'
Regards,
Jenny
Did you name a file in the current directory ldap.py that is shadowing the one that you want?
Many people are giving much more complicated solutions... Simply put, the pip installation of the ldap module doesn't work. You need to install the python-ldap package from apt or yum. Note that the deb package is now named python3-ldap, after the deprecation of python 2.
An easy way to tell if the ldap you're importing is the right one is to print ldap.__file__, which prints the full path to the module file (usually a '.pyc'). If it's not the one installed in the location you are expecting, this is your problem, as Mike Graham suggested.
I did the ldap connection successfully. How to go:
1.I have python v 3.7.2
2.Install python-ldap:For this I tried "pip install python-ldap" but it not worked
for me on windows machine so I use the alternate below.
3.For installing ldap go here:https://www.lfd.uci.edu/~gohlke/pythonlibs/#python-ldap
and download python_ldap‑3.1.0‑cp37‑cp37m‑win_amd64.whl
4.Now move to the download directory and run "pip install
python_ldap‑3.1.0‑cp37‑cp37m‑win_amd64.whl"
Now open python shell and check "import ldap" if you are getting no error means you are done.
This is the sample code:
#Resource of code :https://gist.github.com/ibeex/1288159
import ldap
def check_credentials(username, password):
"""Verifies credentials for username and password.
Returns None on success or a string describing the error on failure
# Adapt to your needs
"""
LDAP_SERVER = 'xxx'
# fully qualified AD user name
LDAP_USERNAME = '%s#spi.com' % username
# your password
LDAP_PASSWORD = password
base_dn = 'DC=spi,DC=com'
ldap_filter = 'userPrincipalName=%s#spi.com' % username
attrs = ['memberOf']
try:
# build a client
ldap_client = ldap.initialize(LDAP_SERVER)
# perform a synchronous bind
ldap_client.set_option(ldap.OPT_REFERRALS,0)
ldap_client.simple_bind_s(LDAP_USERNAME, LDAP_PASSWORD)
except ldap.INVALID_CREDENTIALS:
#print("wron")
ldap_client.unbind()
return 'Wrong username or password'
except ldap.SERVER_DOWN:
#print("down")
return 'AD server not awailable'
# all is well
# get all user groups and store it in cerrypy session for future use
ab = str(ldap_client.search_s(base_dn,
ldap.SCOPE_SUBTREE, ldap_filter, attrs)[0][1]['memberOf'])
#print("ab"+ab)
ldap_client.unbind()
return 'success'
if __name__ == "__main__":
u="chirag"
p="secred"
print(check_credentials(u,p))
You can get that error if you're somehow picking up the "ldap.py" from sos/plugins/ instead of the ldap package itself. Make sure the "python-ldap" package is actually installed...
I guess you have installed "pip install ldap"! In this module "initialize" or "open" are not present.
Uninstall that "ldap" by "pip uninstall ldap" and then try "yum install python-ldap". And run the same code.
Print the "con".
open does not exist anymore in version 3.x of python-ldap.
I fixed it by forcing the installation of an older version :
pip install python-ldap==2.4.13

Categories

Resources