[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x

Python

Python is a widely used general-purpose, high-level programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than would be possible in other languages. Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles. It features a dynamic type system and automatic memory management and has a large and comprehensive set of standard libraries, including NumPy, SciPy, Django, PyQuery, and PyLibrary.

Share tech news, updates, or what's on your mind.

Sign up to Post

I need to read through 1000's of config files and get a list of all VLANs, their description and their IP address and mask. The data looks like:

interface Vlan100
  description Just a vlan
  no shutdown
  no ip redirects
  ip address 1.1.1.1/26

interface Vlan200
  description Just aother vlan
  no shutdown
  no ip redirects
  ip address 2.2.2.2/26

And there lots of other configuration data in the config file that I don't care about. What I have right now is a python program that opens the config file, and reads through looking for 3 strings: "interface Vlan", "  description", and "ip address". The problem, if you know Cisco, is that 2 of those strings occur in places other than vlan definitions.

I am trying to work through the logic of:

Find the line that contains "interface Vlan"
Write that line
and read the lines looking for "description" and "ip address" UNTIL I find another line that says "interface Vlan"

Make sense? I can run the python script now and then delete all the lines up until the first VLAN line and then delete all the lines afterword. But that will be very time consuming for all the files I have to work with.

Thanks in advance for your help.

Steve
0
C++ 11 Fundamentals
LVL 12
C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

Is it possible in Java to connect to the bitcoin.de websocket?
Here is Python 2.7 / Twisted
https://raw.githubusercontent.com/matthiaslinden/bitcoinDE_API/master/bitcoinDEws.py

It is hard to understand what exactly should be sent to bitcoin.de to make it upgrade to WebSocket.
0
I am trying to find a way to query the configuration of an Azure load Balancer using an API and either powershell or python script to populate two fields in the API, the ResourceGroup name and the Subscription ID. The output will need to be in a JSON or XML format.
0
I have a Tkinter application (python 2.7) that copies , configures , remove files. During this operation, I would like to pop up a please wait message box without any buttons while the process is running to inform the users What is the best way to do this.
Thank you for your Quick Prompts.
0
Dear Experts

I have a question about python and mysql interaction. I have big table which contains column named DATETEXT, which simply contains full datetime in text format, like "Fri, 09 Aug 2013 18:46:10 +0200", I need to convert it to datetime value which is not a problem, but I need to update another column in the same table with this value.

So my question is how to update one columns in table X based on value of another column in table X.

Many thanks

Vladimir
0
Dear Experts,

I would need to create a .bat file under Windows, which is able to:

1) run a .py so Python file and
2) also containing credentials as the Python code needs to connect to SQL and download data.

Could you please advise about the syntax how such .bat file should look like concretely?

Actually having the following try but it does not work (it executes the Python code but not asking for the password for the user):

@echo off
runas /netonly /user:smea\csehz
"C:\Python27\python.exe" "C:\Users\csehz\Desktop\HelloWorld.py"
pause

Open in new window


Thanks in advance,
0
hi,

error when running python script to remove VM from the output JSON file. Thanks

# nano destroy_all_vms.py
# python destroy_all_vms.py
/usr/lib/python2.7/site-packages/urllib3/connectionpool.py:769: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.org/en/latest/security.html
  InsecureRequestWarning)
Traceback (most recent call last):
  File "destroy_all_vms.py", line 29, in <module>
    res = delete_vm(vm_id, access_token)
NameError: name 'vm_id' is not defined

delete python script

from fusion import delete_volume
from fusion import delete_vm
from fusion import get_token
import json
import os
from time import sleep
from os.path import isfile, join

mypath = 'outputs'
time_delay = 20

## get all files inside hte outputs directory
onlyfiles = [f for f in os.listdir(mypath) if (isfile(join(mypath, f)) and (f.find('.json') > 0) )]

if len(onlyfiles) > 0:
    access_token = get_token()

for f in onlyfiles:
    vm_file_path = "outputs/" + f

    with open(vm_file_path) as vm_file:
        vm_data = json.load(vm_file)
        for vm in vm_data:
            volume_id = vm['volume_id']

            ## TODO: Check for the existence of the
            ## VM and volume and move forward

            res = delete_vm(vm_id, access_token)
            if res:
                print("Deleted {0} VM successfully.".format(vm['name']))

       …
0
I'm trying to scrape available flatshares from certain websites for personal use and I wonder what's the most productive tool that will be flexible enough to scrape all portals and what will be the most automated tool, that can just ask for a URL and in seconds provide a consumable feed, ideally with minimum fees or no fees (downloadable or buildable solution)?
0
Hi,

 I've never install,configure and test Gitlab runner on Cloud VM (redhat 7.5 ) for version control of my Python Script.

Anyone help guide me through.

Thanks
0
Hello,

i started new for python, i would like know the equivalent python code for below shell script.

#!/bin/bash
data=?fields=attachment
while read n
do
        curl -u admin:admin@123 -X GET https://jira-dev.abc.com/rest/api/2/issue/$n$data | /usr/bin/jq '.id' >> isad.csv

done < filename

where filename contains
SEC-1
SEC-2
SEC-3

regards
Lingesh
0
OWASP: Threats Fundamentals
LVL 12
OWASP: Threats Fundamentals

Learn the top ten threats that are present in modern web-application development and how to protect your business from them.

Hi,

i've tried installing python 3.7.1 to run python code on redhat 7.5 but encountered error. see screenshot. Thanks

error1
python3_error1.jpg
error2
python3_error2.jpg
Another error
#python get-pip.py

error3
python3_error3.jpg
0
hi,

I ran Python Script thr automation for VM creation but only created system volume with error message.

"VM-0001","{'badRequest': {'message': 'Block Device Mapping is Invalid: Boot sequence for the instance and image/block device mapping combination is not valid.', 'code': '400'}}"

Can create VM instance thr GUI for Windows 2016 Sever

VM1.jpg
0
I Have a python script that reads RSS Feeds and returns the results it as a chatbot. Sadly I am not too familiar with python yet. I was requested to "Shorten" the urls that the script returns so it does not create very lengthy links as replies. Using something such as Bit.ly but I am not sure how to start. If someone can point me in the right direction that would help.

I did make some attempts using this but they failed. I was not sure the proper way to use it
https://pypi.org/project/short_url/

Edit, I am using Miniconda and Python 2.7


import re
import os
import sys
import json
import time
import types
import string
import socket
import threading
import feedparser
import short_url

import supybot.conf as conf
import supybot.utils as utils
import supybot.world as world
from supybot.commands import *
import supybot.utils.minisix as minisix
import supybot.ircmsgs as ircmsgs
import supybot.ircutils as ircutils
import supybot.registry as registry
import supybot.callbacks as callbacks
from supybot.i18n import PluginInternationalization, internationalizeDocstring
_ = PluginInternationalization('RSS')

if world.testing:
    INIT_DELAY = 1
else:
    INIT_DELAY = 10

if minisix.PY2:
    from urllib2 import ProxyHandler
else:
    from urllib.request import ProxyHandler

def get_feedName(irc, msg, args, state):
    if ircutils.isChannel(args[0]):
        state.errorInvalid('feed name', args[0], 'must not be channel names.')
    if not 

Open in new window

0
Hello

I am trying to connect Zapier on an MS SQL 2014 instance I am running on one of our servers.

I can connect fine using heidisql.

When connecting from Zapier I get an authentication error:

(pyodbc.ProgrammingError) ('42000', "[42000] [unixODBC][FreeTDS][SQL Server]Login failed for user 'someuser'. (18456) (SQLDriverConnect)")

Open in new window


So this means that the network connexion itself is working but somehow their Python based connector doesn't manage to authenticate.

We used mixed mode authentication on said sever and I have tried both SQL user and domain user to no avail... Using a complex password as per their suggestions.

Any suggestion / info most welcome (as their support is not too helpful on this one).
0
I would like to know if it's possible to retrieve an hashed password from ADAM with Python?

I've seen that DSInternals could allow that, but wouldn't work with ADAM.  Plus we don't need the password in clear text, just the hashed version.

(Using Windows Server 2012 R2, ADAM, Python 3.7)

Thanks
0
Hi:

 I need to add a 2nd degree polynomial to my pandas dataset. Not sure how?

import numpy as np
from sklearn.preprocessing import PolynomialFeatures
poly = PolynomialFeatures(2)
poly.fit(X_tr)


X_tr = ?
0
c++ Python program with Minizinc

In this project, you will design and implement a resource management module for an Operating System Simulator ‘oss’. In this project, you will use the deadlock avoidance to manage resources, with processes being blocked on their requests until those requests are safe.
There is no scheduling in this project, but you will be using shared memory so be cognizant of possible race conditions.

Please see the attached files customer has given me piece of codes and SOP document if someone can help me to understand whats the expectation of customer and how to met that expectation i will be very thankful.
1
Getting errors setting up SublimeText 3 user keymap for View-In-Browser plugin..

My View In Browser settings.sublime-settigs are:
{
	"posix": {
		"darwin": {
			"firefox": "open -a \"/Foreign Apps/Firefox/Firefox Developer Edition.app\"",
			"safari": "open -a \"/Applications/Safari.app\"",
			"chrome": "open -a \"/Foreign Apps/Google/Google Chrome.app\"",
			"opera": "open -a \"/Foreign Apps/Opera/Opera.app\""
		}
	},

	"browser": "firefox"
}

Open in new window


My Default (OSX).sublime-keymap-User are:
[
 
 { "keys": [ "super+e" ], "command": "view-in-browser" },
 { "keys": [ "alt+1” ], “command”: “view_in_browser”, “args”: { “browser”: "firefox" } },
 { "keys": [ "alt+2" ], "command": "view-in-browser", "args": { "browser": "chrome" } },
 { "keys": [ "alt+3" ], "command": "view-in-browser', “args”: { “browser”: “safari” } },
 { "keys": [ "alt+4" ], "command": "view-in-browser", "args": { "browser": "opera" } }
 
]

Open in new window


python console shows: "Error trying to parse file: Unexpected character, expected a comma or closing bracket in Packages/User/Default (OSX).sublime-keymap:4:95"

Can somebody point out the error, because I just can't see it.
0
I have a public API endpoint that I am pulling a json file every 30 mins. Right now I am using a python pandas dataframe to pull and upload the file to a cloud storage bucket and then sending to pub sub to process and place into BQ. The problem with this is that the file name stays the same and even though I have  gcs text stream to pub sub if it reads the file once it never reads it again even though the file attributes have changed. My question here is can any one help me with code that will pull from an api web link and stream the data directly to pub sub?

Sample code below:
import json
import pandas as pd
from sodapy import Socrata
from io import StringIO
import datalab.storage as gcs
from google.oauth2 import service_account

client = Socrata("sample.org", None)
results = client.get("xxx")

# Convert to pandas DataFrame
results_df = pd.DataFrame.from_records(results, columns =['segmentid','street','_direction','_fromst','_tost','_length','_strheading','_comments','start_lon','_lif_lat','lit_lon','_lit_lat','_traffic','_last_updt'])
# send results to GCP
gcs.Bucket('test-temp').item('data.json').write_to(results_df.to_json(orient='records', lines=True),'text/json')
0
Angular Fundamentals
LVL 12
Angular Fundamentals

Learn the fundamentals of Angular 2, a JavaScript framework for developing dynamic single page applications.

well  how can I decode the emails  so i can get plain text?

import poplib;

import io;

import string;

import encodings;

try:

 server = poplib.POP3_SSL("pop.gmail.com",poplib.POP3_SSL_PORT);

   

except:

 print("Error");



response = server.user('XXXXXXXX@gmail.com');

response1 =  server.pass_('XXXXXXXX');

print(response);

print(response1);



# download the first message in the list


messages = server.list();

print(messages);
   

























  

Open in new window


help appreciated
0
Hi, need help to create 1000 VMs to map with direct network ID from python script to call API but it didn't well.

Direct network error: private cloud contains network[1c948756-db50-4871-b03d-d911ecdcae16]', 'code': '400'}}"

Virtual Private Cloud no issue but just can't ping the IP from Python Script being created but when using UI to create and point to the direct network is okay.

Where can i find the right API call to query the direct network ID?

You see click on the below link to download  from google Drive to view the creation process for better understand.

https://drive.google.com/file/d/1ZgYSXrUiODPQk_v6HV7sUZD_UpQ6DMJQ/view?usp=sharing

Thanks.
0
hi, how to understand and resolve this error when deleting 1000VMs from python script. Tks

message":"The maximum request receiving rate is exceeded","request_id
0
Need a python script to copy yesterday files to a destination location and gzip them in destination directory
0
Hi,

Ps advice the below error which require python code to report output status like created successfully of VM of cloud. Tks.

Code:




Error
C:\Users\P1319181\PycharmProjects\fusion\venv\Scripts\python.exe C:/Users/P1319181/PycharmProjects/fusion/main_v1.py
How many volumes/VMs you want to create: 1
Enter the start number: 1
C:\Users\P1319181\PycharmProjects\fusion\venv\lib\site-packages\urllib3\connectionpool.py:852: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
  InsecureRequestWarning)
C:\Users\P1319181\PycharmProjects\fusion\venv\lib\site-packages\urllib3\connectionpool.py:852: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
  InsecureRequestWarning)
C:\Users\P1319181\PycharmProjects\fusion\venv\lib\site-packages\urllib3\connectionpool.py:852: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
  InsecureRequestWarning)
Traceback (most recent call last):
  File "C:/Users/P1319181/PycharmProjects/fusion/main_v1.py", line 71, in <module>
    json.dump(error_file, error_data)
  File …
0
Dear Experts

I am reading in Python eml files, in this format I keep my archived emails. I am just starting with python so I usually stop quite often realizing that I cannot manage something which must be quite easy.

Now I stopped on international header, exactly From:

There is this string in email file right after keyword From: =?UTF-8?Q?Martin_Bo=C4=8Dan_ACTIVE24?= <helpdesk@active24.cz>

It is simply name of operator from big Czech internet company providing internet services. that name correctly displayed is "Martin Bočan ACTIVE24 <helpdesk@active24.cz>"

Is there a way I can decode that string and work with it?

Many thanks

Vladimir
0

Python

Python is a widely used general-purpose, high-level programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than would be possible in other languages. Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles. It features a dynamic type system and automatic memory management and has a large and comprehensive set of standard libraries, including NumPy, SciPy, Django, PyQuery, and PyLibrary.