How Do You Write to a File with Python?

Problem scenario
You want to store variable values in a log file.  How do you get Python to write to a log file?

Solution
Use these lines in your Python program:

var1 = 'contint'

with open('contint.log', 'a') as contint_log:
    contint_log.write("\n")  # creates a new line
    contint_log.write(var1)
    contint_log.write("Done writing variable.\n") # template text

How Do You Install SonarQube Scanner on a RHEL Server?

Update on 2/10/22: The Python example is a little dated. Back when Python 2.x was common, the print statements didn't necessarily have parentheses.

Problem scenario
SonarQube does not work without a launcher installed.  The web UI seems complete, but it is not.  You need a CLI launcher of some sort on the back-end.  You want to use sonar-scanner from the command prompt to analyze some code.  You have installed SonarQube and configured it so the web UI front end allows you to log in.  How do you install the sonar-scanner command line interface tool?

Solution
Prerequisites

i.  You must have SonarQube installed.  If you need directions, see this posting.

ii.  Install unzip if it is not already installed.  To install it, run this command: sudo yum -y install unzip

Procedures
1.  Download the .zip file from SonarQube's website.  (Go to the link.  Click on the link for the Community Edition if you do not want to pay and can agree to the terms.)

2.  Expand the .zip file in a directory of your choice on a Linux server.  You may want to move the .zip file to /opt/ and run this command:

sudo unzip sonar-scanner-cli*.zip

3.  Run this command:  ls

4.  Prepare (or draft) a command such as this, but replace "LastPart" with the last portion of the directory name of the new directory created from step #2 as displayed in step #3:  sudo mv sonar-scanner-LastPart sonar-scanner
Run this command once you prepare it.

5.  Go to /opt/sonar-scanner/conf

6.  Modify the sonar-scanner.properties file.  Uncomment out this line and replace "localhost" with the hostname of the server:

#sonar.host.url=http://localhost:9000

Replace 9000 with the port number you used if you used a non-default port number when you configured the sonar.properties file.

7.  In the /opt/sonar-scanner/conf directory, create a sonar-project.properties file.  Place the following content in it:

# "Contint" must be unique in a given SonarQube instance
sonar.projectKey=Contint
# "Contint" is the name and version displayed in the SonarQube UI. Was mandatory prior to SonarQube 6.1.
sonar.projectName=Contint
sonar.projectVersion=1.0

# Path is relative to the sonar-project.properties file. Replace "\" by "/" on Windows.
# This property is optional if sonar.modules is set.
sonar.sources=contint

8.  In the /opt/sonar-scanner/conf/ directory create a new directory called contint.  (If you want to have you sonar-scanner command look in a different directory for source code files to analyze, do not create the contint directory.  Modify the sonar-project.properties file so the stanza sonar.sources= stanza points to the location of your choice.)

Create a Python file and Java file in this directory.

Here is an example of a Java program called hello.java:

public class HelloWorld {

    public static void main(String[] args) {

        System.out.println("Hello, World");
    }

}

Here is an example of a Python program called hello.py:

var1 = 'hello'
print var1

9.  Run this command: sudo /opt/sonar-scanner/bin/sonar-scanner -X

10.  Open the web UI for SonarQube and log in.  If you are not using a web server the URL is often http://x.x.x.x:9000/sonar where x.x.x.x is the external IP address of the server.  The default credentials are usually admin / admin.  If you are using a web server (e.g., Apache web server), just go to http://x.x.x.x where x.x.x.x is the external IP address of the server.

11.  Go to "Projects" in the web UI.  You should see one called "Contint" if you followed the above directions (because of step #7).  Click on the hyperlink.

12.  Click on the directory called "contint" as it should be named as such because of step #8.  

13.  You should see the .java and .py files in the GUI now; these files were created in step #8.  You can click on "Issues" near the top to see more about what SonarQube has found with the code.  If you used the examples above, the hello.py file should cause a message about the print statement.  A preferred way of using the print statement is to put parentheses around the variable like this:

print(var)

14.  You are now done.

How Do You Capture Error Messages in a File of Your Choice Using Python Rather Than Have Them Printed to the Screen?

Problem scenario
You have a Python program that displays urllib3 (or some other type) of message to the screen.  You do not want them echoed there cluttering the screen.  You want to redirect the output to a log file (to permanently store the data).  How do you get a Python program to write to a log file?

Solution
Use these three lines, but replace "contint" with the name of your choice:

import logging

logging.basicConfig(filename='contint.log', filemode='a', level=logging.DEBUG)
logging.captureWarnings(True)

How Do You Get a Jenkins Plugin to Work That Normally Uses the Internet When You Have No Internet Access?

Problem scenario
Your Jenkins server has no access to the internet.  You are trying to run a  Jenkins job that involves a plugin.  You receive a 407 error when a job runs.  You look at the console output and see java.io error that deals with being unable to connect to a website.  How do you customize a Jenkins plugin to retrieve installation media from an internal server instead of a default website URL?

Solution
Go to Manage Jenkins -> Global Tool Configuration.  Find the plugin.  Modify the plugin configuration there.

Why Cannot You Use a Python Module in a Program or the Command Prompt When One Will Work but Not the Other?

Problem scenario
You have a Python program use an import statement, but the program fails.  From the Python command prompt, you can import the module.  Why is it different?

Possible Solution #1
You may be using Python version 3 for either the command prompt or the program and Python version 2 for the complement (either the command prompt or the program). Try these commands:

python --version
python3 --version

Possible Solution #2
See where the potential imports are. Enter the Python command prompt once with python (or python2) and a second time with python3 (or python). Then run these two commands from that line (where >>> is just a reference a not part of the command itself):

>>> import sys
>>> print(sys.path())

Possible Solution #3
In the Python program, temporarily add these two lines, purely as a diagnostic, before the import line that is causing the problem, and run your program:

import sys
print(sys.path)

How Do You Get the Sonar Scanner Tool to Be Reinstalled on a Jenkins Slave?

Problem scenario
You want to uninstall the Sonar Scanner CLI to force its reinstallation as you have a Jenkins job that does the installation automatically.  What do you do to uninstall it and make the Jenkins job do the installation again?

Solution
1.  For the Sonar Scanner job that will run, configure it so it runs on a specific slave.  Log into Jenkins.  Go to the Jenkins job, go to Configure, and search for the word "Restrict".  Check the box near this word.  For the "Label" field, type in the hostname of the Linux server that has Sonar Scanner.

2.  Go to "Manage Jenkins".  Go to "Global Tool Configuration".   Go to SonarQube Scanner Installations.  Look at the "Name" field.  Remember the value.

3.  Log into the back end of the Jenkins slave that has Sonar Scanner installed.  Run this command but replace "foobar" with the value found in step #2:  sudo find / -name foobar | grep SonarRunnerInstallation

4.  Move the directory (e.g., /home/jenkins/jenkins_slave/tools/hudson.plugins.sonar.SonarRunnerInstallation/contint) that was found above to your user's home directory or somewhere in a completely different path (e.g., /tmp/).

5.  Re-run the Jenkins job.  The installation should be triggered from the absence of the directory on the slave server as Jenkins has a "remote directory" to look for.

How Do You Get a GCP Server to Present a Website on the Internet?

Problem scenario
You want to browse the web UI of a web application that you set up on a Linux machine in GCP.  How do you get a web service (e.g., Nginx, Apache web server, SonarQube or Jenkins) to work when the server is in Google Cloud Platform?

Solution
Prerequisites
This assumes you have deployed the web application.  If you want to deploy Nginx, see this link.  If you want to deploy Apache web server, see this link.  If you want to install SonarQube, see this link.  If you want to deploy Jenkins, see this link.

Procedures
Overview:  Create a firewall rule from the source IP address of your web browser. 

1.  After you are logged into GCP go to VPC Network -> Firewall Rules. 
2.  Click on "Create firewall rule".
3.  To find the source IP address go to the workstation where you will browse from and go to ipchicken.com
4.  The port may vary (e.g., for SonarQube you may need 9000 or for Jenkins you may need 8080).  If you want the application to work from any workstation, use the source IP address range of "0.0.0.0/0" with no quotes.  
5.  For a Tag, enter an alphanumeric string.  Remember the tag you give this rule.
6.  Next go to "Compute Engine" -> "VM Instances" page. 
7.  Click on the hyperlink for the VM that has the web service. 
8.  Click on "Edit" to modify the details. 
9.  In the "Network Tags" field, enter the unique tag you entered above (the alphanumeric string).  
10.  Go to the Firewalls section.  Click the boxes for "Allow HTTP traffic" and "Allow HTTPS traffic".
11.  Click "Save".  The changes will take effect after a few minutes.

How Do You Troubleshoot the Error “Invalid Option” When Trying to Delete a File That Has a File Name with the First Character Being a Hyphen or Dash “-“?

Problem scenario
You have some files that have a name that starts with a hyphen (e.g., from some Bash script that did not work as intended):

-the
-filename
-q

You cannot delete them using rm.  You get an error about an "invalid option".  What should you do to delete this files that should never have been created in the first place?

Solution
Use the rm flag "--" such as this:

rm -- -the
rm -- -filename
rm -- -q

How Do You Find Your Phone Number with an Android Phone?

Problem scenario
You are using an Android phone, and you want to find its phone number.

Solution
1.  Turn on your Android phone.
2.  Go to Tools -> Settings
3.  Scroll down to the "System" section and click on About phone ->  SIM status.  You should see the phone number at the bottom.

If you want to buy a new Android phone, you can click here.

How Do You Test the Database Credentials (username and password) of a PostgreSQL Database Using Bash?

Problem scenario
You are not sure if the username and password to a PostgreSQL database work.  What do you do?

Solution
Run this one-line command:

psql -d "postgresql://jdoe:coolpassword@localhost/foobardb" -c "select now()"

# Replace "jdoe" with the SQL database username
# Replace "coolpassword" with the user's password
# Replace "foobardb" with the name of the database you are authenticating too
# If you have the PostgreSQL client installed (so psql works) and the database is remote, use the FQDN instead of the "localhost"

This solution was based on this posting.