Why can not YCM edit its own buffer?
Diagnostics refreshed
Error detected while processing function <SNR>187_ShowDiagnostics:
line 1:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/home/ubuntu/.vim/plugged/YouCompleteMe/python/ycm/youcompleteme.py", line 832, in ShowDiagnostics
vimsupport.OpenLocationList( focus = True )
File "/home/ubuntu/.vim/plugged/YouCompleteMe/python/ycm/vimsupport.py", line 385, in OpenLocationList
vim.command( 'lopen' )
vim.error: Vim(loadview):E788: Not allowed to edit another buffer now
My .ycm_extra_conf.py:
# This file is NOT licensed under the GPLv3, which is the license for the rest
# of YouCompleteMe.
#
# Here's the license text for this file:
#
# This is free and unencumbered software released into the public domain.
#
# Anyone is free to copy, modify, publish, use, compile, sell, or
# distribute this software, either in source code form or as a compiled
# binary, for any purpose, commercial or non-commercial, and by any
# means.
#
# In jurisdictions that recognize copyright laws, the author or authors
# of this software dedicate any and all copyright interest in the
# software to the public domain. We make this dedication for the benefit
# of the public at large and to the detriment of our heirs and
# successors. We intend this dedication to be an overt act of
# relinquishment in perpetuity of all present and future rights to this
# software under copyright law.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
# For more information, please refer to <http://unlicense.org/>
import os
import ycm_core
# These are the compilation flags that will be used in case there's no
# compilation database set (by default, one is not set).
# CHANGE THIS LIST OF FLAGS. YES, THIS IS THE DROID YOU HAVE BEEN LOOKING FOR.
flags = [
'-Wall',
'-Wextra',
'-Werror',
'-Wno-long-long',
'-Wno-variadic-macros',
'-DNDEBUG',
# THIS IS IMPORTANT! Without a "-std=<something>" flag, clang won't know which
# language to use when compiling headers. So it will guess. Badly. So C++
# headers will be compiled as C headers. You don't want that so ALWAYS specify
# a "-std=<something>".
# For a C project, you would set this to something like 'c99' instead of
# 'c++11'.
'-std=c99',
# ...and the same thing goes for the magic -x option which specifies the
# language that the files to be compiled are written in. This is mostly
# relevant for c++ headers.
# For a C project, you would set this to 'c' instead of 'c++'.
'-x', 'c',
'-I', '.',
'-I', './src/',
'-I', './include/',
'-I', './ClangCompleter',
'-isystem', '../llvm/include',
'-isystem', '../llvm/tools/clang/include',
'-isystem', './tests/gmock/gtest',
'-isystem', './tests/gmock/gtest/include',
'-isystem', './tests/gmock',
'-isystem', './tests/gmock/include',
'-isystem', '/usr/include',
'-isystem', '/usr/local/include',
'-isystem', './platform',
'-isystem', './platform/base',
'-isystem', './platform/base/RFCGeneral/',
'-isystem', './platform/base/RFCGeneral/event',
'-I', './platform',
'-I', './platform/base',
'-I', './platform/base/RFCGeneral/',
'-I', './platform/base/RFCGeneral/event',
]
# Set this to the absolute path to the folder (NOT the file!) containing the
# compile_commands.json file to use that instead of 'flags'. See here for
# more details: http://clang.llvm.org/docs/JSONCompilationDatabase.html
#
# Most projects will NOT need to set this to anything; you can just change the
# 'flags' list of compilation flags. Notice that YCM itself uses that approach.
compilation_database_folder = ''
if os.path.exists( compilation_database_folder ):
database = ycm_core.CompilationDatabase( compilation_database_folder )
else:
database = None
SOURCE_EXTENSIONS = [ '.cpp', '.cxx', '.cc', '.c', '.m', '.mm' ]
def DirectoryOfThisScript():
return os.path.dirname( os.path.abspath( __file__ ) )
def MakeRelativePathsInFlagsAbsolute( flags, working_directory ):
if not working_directory:
return list( flags )
new_flags = []
make_next_absolute = False
path_flags = [ '-isystem', '-I', '-iquote', '--sysroot=' ]
for flag in flags:
new_flag = flag
if make_next_absolute:
make_next_absolute = False
if not flag.startswith( '/' ):
new_flag = os.path.join( working_directory, flag )
for path_flag in path_flags:
if flag == path_flag:
make_next_absolute = True
break
if flag.startswith( path_flag ):
path = flag[ len( path_flag ): ]
new_flag = path_flag + os.path.join( working_directory, path )
break
if new_flag:
new_flags.append( new_flag )
return new_flags
def IsHeaderFile( filename ):
extension = os.path.splitext( filename )[ 1 ]
return extension in [ '.h', '.hxx', '.hpp', '.hh' ]
def GetCompilationInfoForFile( filename ):
# The compilation_commands.json file generated by CMake does not have entries
# for header files. So we do our best by asking the db for flags for a
# corresponding source file, if any. If one exists, the flags for that file
# should be good enough.
if IsHeaderFile( filename ):
basename = os.path.splitext( filename )[ 0 ]
for extension in SOURCE_EXTENSIONS:
replacement_file = basename + extension
if os.path.exists( replacement_file ):
compilation_info = database.GetCompilationInfoForFile( replacement_file )
if compilation_info.compiler_flags_:
return compilation_info
return None
return database.GetCompilationInfoForFile( filename )
def FlagsForFile( filename, **kwargs ):
if database:
# Bear in mind that compilation_info.compiler_flags_ does NOT return a
# python list, but a "list-like" StringVec object
compilation_info = GetCompilationInfoForFile( filename )
if not compilation_info:
return None
final_flags = MakeRelativePathsInFlagsAbsolute(
compilation_info.compiler_flags_,
compilation_info.compiler_working_dir_ )
# NOTE: This is just for YouCompleteMe; it's highly likely that your project
# does NOT need to remove the stdlib flag. DO NOT USE THIS IN YOUR
# ycm_extra_conf IF YOU'RE NOT 100% SURE YOU NEED IT.
try:
final_flags.remove( '-stdlib=libc++' )
except ValueError:
pass
else:
relative_to = DirectoryOfThisScript()
final_flags = MakeRelativePathsInFlagsAbsolute( flags, relative_to )
return {
'flags': final_flags,
'do_cache': True
}
The output of `:YcmDebuggInfo"
Printing YouCompleteMe debug information...
-- Resolve completions: Up front
-- Client logfile: /tmp/ycm_iifk1o7e.log
-- Server Python interpreter: /usr/bin/python3
-- Server Python version: 3.8.10
-- Server has Clang support compiled in: False
-- Clang version: None
-- Extra configuration file found and loaded
-- Extra configuration path: /home/ubuntu/workspace/proj/.ycm_extra_conf.py
-- C-family completer debug information:
-- Clangd running
-- Clangd process ID: 14913
-- Clangd executable: ['/home/ubuntu/.vim/plugged/YouCompleteMe/third_party/ycmd/third_party/clangd/output/bin/clangd', '-log=verbose', '-pretty', '-header-insertion-decorators=0', '-resource-dir=/home/ubuntu/.vim/plugged/YouCompleteMe/third_party/ycmd/third_party/clang/lib/clang/13.0.0']
-- Clangd logfiles:
-- /tmp/clangd_stderr5hvc2xhc.log
-- Clangd Server State: Initialized
-- Clangd Project Directory: /home/ubuntu/workspace/roc_rsp_shell
-- Clangd Settings: {}
-- Clangd Compilation Command: False
-- Server running at: http://127.0.0.1:43927
-- Server process ID: 14873
-- Server logfiles:
-- /tmp/ycmd_43927_stdout_qts9v8rd.log
-- /tmp/ycmd_43927_stderr_saz7qf73.log
Press ENTER or type command to continue
Related
I have made a simple kivy app using also the socket module. But when I try to convert it to an android app using google collab and buildozer, I am getting this kind of an error.
{
ERROR: Could not find a version that satisfies the requirement socket (from versions: none)
ERROR: No matching distribution found for socket
STDERR:
# Command failed: /usr/bin/python3 -m pythonforandroid.toolchain create --dist_name=starstocksapp --bootstrap=sdl2 --requirements=python3,socket,kivy --arch armeabi-v7a --copy-libs --color=always --storage-dir="/content/.buildozer/android/platform/build-armeabi-v7a" --ndk-api=21
# ENVIRONMENT:
# CUDNN_VERSION = '8.0.5.39'
# PYDEVD_USE_FRAME_EVAL = 'NO'
# LD_LIBRARY_PATH = '/usr/local/nvidia/lib:/usr/local/nvidia/lib64'
# CLOUDSDK_PYTHON = 'python3'
# LANG = 'en_US.UTF-8'
# HOSTNAME = '047d4a118941'
# OLDPWD = '/'
# CLOUDSDK_CONFIG = '/content/.config'
# NVIDIA_VISIBLE_DEVICES = 'all'
# DATALAB_SETTINGS_OVERRIDES = '{"kernelManagerProxyPort":6000,"kernelManagerProxyHost":"172.28.0.3","jupyterArgs":["--ip=\\"172.28.0.2\\""],"debugAdapterMultiplexerPath":"/usr/local/bin/dap_multiplexer","enableLsp":true}'
# ENV = '/root/.bashrc'
# PAGER = 'cat'
# NCCL_VERSION = '2.7.8'
# TF_FORCE_GPU_ALLOW_GROWTH = 'true'
# JPY_PARENT_PID = '53'
# NO_GCE_CHECK = 'True'
# PWD = '/content'
# HOME = '/root'
# LAST_FORCED_REBUILD = '20211007'
# CLICOLOR = '1'
# DEBIAN_FRONTEND = 'noninteractive'
# LIBRARY_PATH = '/usr/local/cuda/lib64/stubs'
# GCE_METADATA_TIMEOUT = '0'
# GLIBCPP_FORCE_NEW = '1'
# TBE_CREDS_ADDR = '172.28.0.1:8008'
# TERM = 'xterm-color'
# SHELL = '/bin/bash'
# GCS_READ_CACHE_BLOCK_SIZE_MB = '16'
# PYTHONWARNINGS = 'ignore:::pip._internal.cli.base_command'
# MPLBACKEND = 'module://ipykernel.pylab.backend_inline'
# CUDA_VERSION = '11.1.1'
# NVIDIA_DRIVER_CAPABILITIES = 'compute,utility'
# SHLVL = '1'
# PYTHONPATH = '/env/python'
# NVIDIA_REQUIRE_CUDA = ('cuda>=11.1 brand=tesla,driver>=418,driver<419 '
'brand=tesla,driver>=440,driver<441 brand=tesla,driver>=450,driver<451')
# COLAB_GPU = '0'
# GLIBCXX_FORCE_NEW = '1'
# PATH = '/root/.buildozer/android/platform/apache-ant-1.9.4/bin:/usr/local/nvidia/bin:/usr/local/cuda/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/tools/node/bin:/tools/google-cloud-sdk/bin:/opt/bin'
# LD_PRELOAD = '/usr/lib/x86_64-linux-gnu/libtcmalloc.so.4'
# GIT_PAGER = 'cat'
# _ = '/usr/local/bin/buildozer'
# PACKAGES_PATH = '/root/.buildozer/android/packages'
# ANDROIDSDK = '/root/.buildozer/android/platform/android-sdk'
# ANDROIDNDK = '/root/.buildozer/android/platform/android-ndk-r19c'
# ANDROIDAPI = '27'
# ANDROIDMINAPI = '21'
#
# Buildozer failed to execute the last command
# The error might be hidden in the log above this error
# Please read the full log, and search for it before
# raising an issue with buildozer itself.
# In case of a bug report, please add a full log with log_level = 2
}
I don't know why this error keeps on coming. I have my main.py in the directory and I have checked to install all the modules. But still nothing happens.
I think socket module is not included or some problem is due to that I am including socket module. I have written the socket module's name in the spec file also in the modules to be included.
Thanks in Advance.
You don't have to add socket in requirements of your buildozer.spec file as they are inbuild modules in python. So, they will automatically get added when you add python3 in your requirements.
See this post for more info:
Buildozer not using correct kivy version when packaging for android
I am a hobby radio amateur [G6SGA] not a programmer but I do try. :)
using python3. I am trying to do the following and really can't get my head around - argparse and ended up trying to use 'Import click'. Still can't get my head around so here I am. Any all (polite) :) suggestions welcome.
I wish to ---
cmd line> python3 scratch.py [no options supplied]
output> "Your defaults were used and are:9600 and '/dev/ttyAMA0' "
or
cmd line> python3 scratch.py 115200 '/dev/ttyABC123'
output> "Your input values were used and are: 115200 and '/dev/ttyAMA0'"
so a command line that will take [or NOT] argument/s. store the argument to a variable in the code for future use.
This some of what I have tried: Yes I accept it's a mess
#!/usr/bin/env python3
# -*- coding: utf_8 -*-
# ========================
# Include standard modules
# import click
# baud default = 9600
# port default = "/dev/ttyAMA0"
import click
#click.command()
# #click.option('--baud', required = False, default = 9600, help = 'baud rate defaults to: 9600')
# #click.option('--port', required = False, default = '/dev/ttyAMA0', help = 'the port to use defaults to: /dev/ttyAMA0')
#click.option('--item', type=(str, int))
def putitem(item):
click.echo('name=%s id=%d' % item)
def communications():
""" This checks the baud rate and port to use
either the command line supplied item or items.
Or uses the default values
abaud = 9600 # default baud rate
b=abaud
aport = "/dev/ttyAMA0"
p=aport
print(f"abaud = {b} and aport = {p}")
"""
# now I wish to check if there were supplied values
# on the command line
# print(f"Baud supplied {click.option.} port supplied {port}" )
if __name__ == '__main__':
putitem() # communications()
The code I have used to work this all out is below, I hope it helps somebody. Any better ways or mistakes please advise.
#!/usr/bin/env python3
# -*- coding: utf_8 -*-
import click
from typing import Tuple
# Command Line test string: python scratch_2.py -u bbc.co.uk aaa 9600 bbb ccc
myuri = "" # This is a placeholder for a GLOBAL variable -- take care!
list1 = [] # This is a placeholder for a GLOBAL variable -- take care!
#click.command(name="myLauncher", context_settings={"ignore_unknown_options": True})
#click.option('--uri', '-u', type=click.STRING, default=False, help ="URI for the server")
#click.argument('unprocessed_args', nargs = -1, type = click.UNPROCESSED)
def main(uri: str, unprocessed_args: Tuple[str, ...]) -> None:
# ==================== Checking the command line structure and obtaining variables
global myuri # define the use of a GLOBAL variable in this function
temp = list((str(j) for i in {unprocessed_args: Tuple} for j in i)) # sort out the command line arguments
res = len(temp)
# printing result
print("")
for e in range(0 ,res): # list each of the command line elements not including any uri
print("First check: An input line Tuple element number: " + str(e) +": " + str(temp[e])) # elements base 0
# ==================== deal with any URI supplied -- or NOT
if uri is False: #if --uri or -u is not supplied
print("No uri supplied\n")
print("The input line tuple list elements count: " + str(res))
# set a defaul GLOBAL value of myuri if it is not supplied
myuri = "https://192.168.0.90:6691/" #
else:
print("\nThe input line tuple list elements count : " + str(res) + " and we got a uri")
myuri = uri # set the GLOBAL value of myuri if the uri is
print(f"which is: {uri}, and therefore myuri also is: {myuri}") # a temp print to prove the values of the GLOBAL variable 'myuri'
# ==============================================================================================
# Testing choice of baud rate on command line
db_list = {
'4800': 'TEST48',
'9600': 'TEST96',
'19200': 'TEST19',
'38400': 'TEST38',
'57600': 'TEST57',
'115200': 'TEST11',
}
# Print databases ----- db_list ----- listed in dictionary
print("\nDatabases:")
for e in range(0 ,res) :
""" list each of the command line elements not including any uri
print("Second Check: An input line Tuple element number: " + str(e) +": " + str(temp[e]))
elements base 0 """
if str(temp[e]) in db_list.keys() :
print(f"The index of db contains {str(temp[e])}, The index refers to: {db_list[str(temp[e])]}")
if __name__ == "__main__":
# pylint: disable=no-value-for-parameter, unexpected-keyword-arg
main()
I am writing a python application which is programming and testing atmel microcontrollers through a SPI port.
The application is running on RaspberryPi model 3B+ and I use the command line application 'avrdude' to do the job. I use subprocess.Popen() from within my python script and in general this runs just fine.
Sometimes, the SPI port gets in a blocked state. The avrdude application then typically reports something like 'Can't export GPIO 8, already exported/busy?: Device or resource busy'
One can observe the exported GPIO's by:
pi#LeptestPost:/ $ ls /sys/class/gpio/
export gpio10 gpio11 gpio8 gpiochip0 gpiochip504 unexport
I get out of this situation by invoking:
pi#LeptestPost:/ $ sudo echo 8 > /sys/class/gpio/unexport
resulting in:
pi#LeptestPost:/ $ ls /sys/class/gpio/
export gpio10 gpio11 gpiochip0 gpiochip504 unexport
So I can unexport them all and move on manually but I would like to have this automated in the application with the following code (after detecting the error in the avrdude output):
args = ['sudo', 'echo', '8', '>', '/sys/class/gpio/unexport']
result, error = self.runCommand(args, wait=True)
def runCommand(self, args, wait = False, outputFileStr = "", errorFileStr = "", workingDir = ""):
# documentation:
#class subprocess.Popen(args,
# bufsize=-1,
# executable=None,
# stdin=None,
# stdout=None,
# stderr=None,
# preexec_fn=None,
# close_fds=True,
# shell=False,
# cwd=None,
# env=None,
# universal_newlines=None,
# startupinfo=None,
# creationflags=0,
# restore_signals=True,
# start_new_session=False,
# pass_fds=(),
# *,
# encoding=None,
# errors=None,
# text=None)
print("Working on executing command " + str(args))
if (outputFileStr != ""):
stdoutFile = open(outputFileStr,'w')
else:
stdoutFile = None
if (errorFileStr != ""):
stderrFile = open(errorFileStr,'w')
else:
stderrFile = None
if (workingDir != ""):
cwdStr = workingDir
else:
cwdStr = None
try:
if (wait):
p = subprocess.Popen(args, stdout = subprocess.PIPE, cwd = cwdStr)
print("started subprocess with PID " + str(p.pid))
p.wait() # Wait for child process to terminate, This will deadlock when using stdout=PIPE or stderr=PIPE
else:
#p = subprocess.Popen(args, stdin = None, stdout = None, stderr = None, close_fds = True)
p = subprocess.Popen(args, stdin = None, stdout = stdoutFile, stderr = stderrFile, close_fds = True, cwd = cwdStr)
print("started subprocess with PID " + str(p.pid))
(result, error) = p.communicate(timeout=15) # Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached.
except subprocess.CalledProcessError as e:
sys.stderr.write("common::run_command() : [ERROR]: output = %s, error code = %s\n" % (e.output, e.returncode))
return e.output, e.returncode
except FileNotFoundError as e:
self.master.printERROR("common::run_command() : [ERROR]: output = %s, error code = " + str(e) + "\n")
return "error", str(e)
except subprocess.TimeoutExpired as e:
self.master.printERROR("Process timeout on PID "+ str(p.pid) + ", trying to kill \n")
p.kill()
outs, errs = p.communicate()
return "error", str(e)
if (outputFileStr != ""):
stdoutFile.close()
if (errorFileStr != ""):
stderrFile.close()
return result, error
But that does not do the job (no error, not the wanted result). I can imagine it's related to how the process is started within its shell or environment - but that's beyond my knowledge.
Any idea how to get this working?
Note: the avrdude application is also called using the 'runcommand' method and running fine.
I'm writing a Python script which expects a regex pattern and a file name and looks for that regex pattern within the file.
By default, the script requires a file to work on.
I want to change the script so by default it would take it's input from STDIN unless a file is specified (-f filename).
My code looks like so:
#!/usr/bin/env python3
# This Python script searches for lines matching regular expression -r (--regex) in file/s -f (--files).
import re
import argparse
#import sys
class colored:
CYAN = '\033[96m'
UNDERLINE = '\033[4m'
END = '\033[0m'
def main(regex, file, underline, color):
pattern = re.compile(regex)
try:
for i, line in enumerate(open(file, encoding="ascii")):
for match in re.finditer(pattern, line):
message = "Pattern {} was found on file: {} in line {}. The line is: ".format(regex, file, i+1)
if args.color and args.underline:
#message = "Pattern {} was found on file: {} in line {}. The line is: ".format(regex, file, i+1)
l = len(line)
print(message + colored.CYAN + line + colored.END, end="")
print(" " ,"^" * l)
break
if args.underline:
l = len(line)
print(message + line, end="")
print(" " ,"^" * l)
break
if args.color:
print(message + colored.CYAN + line + colored.END, end="")
break
if args.machine:
print("{}:{}:{}".format(file, i+1, line), end="")
break
else:
print(message + line, end="")
break
except FileNotFoundError:
print("File not found, please supply")
pass
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Python regex finder', epilog = './python_parser.py --regex [pattern] --files [file]')
requiredNamed = parser.add_argument_group('required named arguments')
requiredNamed.add_argument('-r', '--regex',
help='regex pattern', required=True)
parser.add_argument('-f', '--file',
help='file to search pattern inside')
parser.add_argument('-u', '--underline', action='store_true',
help='underline')
parser.add_argument('-c', '--color', action='store_true',
help='color')
parser.add_argument('-m', '--machine', action='store_true',
help='machine')
args = parser.parse_args()
main(args.regex, args.file, args.underline, args.color)
You can see how a run looks here.
I tried using the answer from this SO question, but getting the following error:
for i, line in enumerate(open(file, encoding="ascii")):
TypeError: expected str, bytes or os.PathLike object, not _io.TextIOWrapper
Edit #1:
This is the file:
Itai
# something
uuu
UuU
# Itai
# this is a test
this is a test without comment
sjhsg763
3989746
# ddd ksjdj #kkl
I get the above error when I supply no file.
Edit#2:
When I change the file argument to that:
parser.add_argument('-f', '--file',
help='file to search pattern inside',
default=sys.stdin,
type=argparse.FileType('r'),
nargs='?'
)
And then run the script like so:
~ echo Itai | ./python_parser.py -r "[a-z]" -m
Traceback (most recent call last):
File "./python_parser.py", line 59, in <module>
main(args.regex, args.file, args.underline, args.color)
File "./python_parser.py", line 16, in main
for i, line in enumerate(open(file, encoding="ascii")):
TypeError: expected str, bytes or os.PathLike object, not NoneType
➜ ~
args.file = tmpfile
which is a file in the same directory where the script runs.
What am I doing wrong?
You wrote this:
def main(regex, file, underline, color):
...
for i, line in enumerate(open(file, encoding="ascii")):
You have some confusion about whether file denotes a filename or an open file descriptor. You want it to be an open file descriptor, so you may pass in sys.stdin. That means main() should not attempt to open(), rather it should rely on the caller to pass in an already open file descriptor.
Pushing the responsibility for calling open() up into main() will let you assign file = sys.stdin by default, and then re-assign the result of open() if it turns out that a filename was specified.
I have a Costco R4500 router that I am trying to open up telnet on. The older telnetenable.py script is what is needed to send a TCP packet to open it up. Then the router can be upgraded/updated, as the only release of firmware available for it from Netgear is terrible.
The new telnetenable2 using UDP packets does work on Windows 10, but does not work on this older firmware. The older exe, telnetenable, using TCP, does not run on Windows 10.
I figured out I had to install Python. Then I have to use Cryptodome instead of Crypto. And apparently Visual Studio. I am not a programmer.
Installed Python, then got the crypto error, then realized the PyCrypto package is not longer maintained, then installed PyCryptoDome, and modified the telnetenable.py somewhat. Only I am not a programmer, so I have very basic knowledge. I have read a lot on the current error I am getting, but have no idea what to do. I have looked at the script, and was hoping someone could tell me what is wrong with it.
copy of code in pastebin
# Copyright (c) 2009 Paul Gebheim...
import sys
import socket
import array
from optparse import OptionParser
from Cryptodome.Cipher import Blowfish
from Cryptodome.Hash import MD5
TELNET_PORT = 23
# The version of Blowfish supplied for the telenetenable.c implementation
# assumes Big-Endian data, but the code does nothing to convert the
# little-endian stuff it's getting on intel to Big-Endian
#
# So, since Crypto.Cipher.Blowfish seems to assume native endianness, we need
# to byteswap our buffer before and after encrypting it
#
# This helper does the byteswapping on the string buffer
def ByteSwap(data):
a = array.array('i')
if(a.itemsize < 4):
a = array.array('L')
if(a.itemsize != 4):
print("Need a type that is 4 bytes on your platform so we can fix the data!")
exit(1)
a.fromstring(data)
a.byteswap()
return a.tostring()
def GeneratePayload(mac, username, password=""):
# Pad the input correctly
assert(len(mac) < 0x10)
just_mac = mac.ljust(0x10, "\x00")
assert(len(username) <= 0x10)
just_username = username.ljust(0x10, "\x00")
assert(len(password) <= 0x10)
just_password = password.ljust(0x10, "\x00")
cleartext = (just_mac + just_username + just_password).ljust(0x70, '\x00')
md5_key = MD5.new(cleartext).digest()
payload = ByteSwap((md5_key + cleartext).ljust(0x80, "\x00"))
secret_key = "AMBIT_TELNET_ENABLE+" + password
return ByteSwap(Blowfish.new(secret_key, 1).encrypt(payload))
def SendPayload(ip, payload):
for res in socket.getaddrinfo(ip, TELNET_PORT, socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_IP):
af, socktype, proto, canonname, sa = res
try:
s = socket.socket(af, socktype, proto)
except socket.error as msg:
s = None
continue
try:
s.connect(sa)
except socket.error as msg:
s.close()
s= None
continue
break
if s is None:
print ("Could not connect to '%s:%d'") % (ip, TELNET_PORT)
else:
s.send(payload)
s.close()
print ("Sent telnet enable payload to '%s:%d'") % (ip, TELNET_PORT)
def main():
args = sys.argv[1:]
if len(args) < 3 or len(args) > 4:
print ("usage: python telnetenable.py <ip> <mac> <username> [<password>]")
ip = args[0]
mac = args[1]
username = args[2]
password = ""
if len(args) == 4:
password = args[3]
payload = GeneratePayload(mac, username, password)
SendPayload(ip, payload)
main()
md5_key = MD5.new(cleartext).digest()
This is where I get the error:
Traceback (most recent call last):
File "telnetenable.py", line 113, in <module>
main()
File "telnetenable.py", line 110, in main
payload = GeneratePayload(mac, username, password)
File "telnetenable.py", line 64, in GeneratePayload
md5_key = MD5.new(cleartext).digest()
File "C:\Users\farme\AppData\Local\Programs\Python\Python36\lib\site-packages\Cryptodome\Hash\MD5.py", line 47, in __init__
self._h = _hash_new(*args)
TypeError: Unicode-objects must be encoded before hashing
It looks to me that the arguments you are passing to the script are in unicode and the MD5 object wants it encoded prior to processing it. I think the encoding will put one symbol per byte rather than allowing any confusion that any multi-byte characters might create if there is also a single byte option for that character.
Try something this:
md5_key = MD5.new(cleartext.encode('utf-8)).digest()