0% found this document useful (0 votes)
14 views10 pages

Questions

The document contains a series of technical questions and answers related to shell scripting, Python programming, and network operations. It includes tasks such as replacing IPv6 addresses with 'IPV6', creating cron jobs, encrypting files, and analyzing logs. Each question is followed by a solution and explanation, covering tools like sed, awk, curl, and Python.

Uploaded by

amal98.alaskari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views10 pages

Questions

The document contains a series of technical questions and answers related to shell scripting, Python programming, and network operations. It includes tasks such as replacing IPv6 addresses with 'IPV6', creating cron jobs, encrypting files, and analyzing logs. Each question is followed by a solution and explanation, covering tools like sed, awk, curl, and Python.

Uploaded by

amal98.alaskari
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

🔸 Q1.

sed & IPv6


Question:
You have a text file network.txt containing IPv6 addresses.
Write a sed command to replace all IPv6 addresses with the word IPV6.
Example line in file:
cpp
CopyEdit
Pinged address: fe80::1ff:fe23:4567:890a

🔸 Q2. awk Domain Mapping


Question:
Given two files:
 servers.txt (contains logs with IPs)
 dns.txt (contains mappings: IP DomainName)
Write an awk script to replace IPs in servers.txt with their domain names using dns.txt.

🔸 Q3. cron
Question:
Write a cron job that:
 Runs a backup script located at /home/student/backup.sh
 Every 15 minutes

🔸 Q4. openssl
Question:
Encrypt a file named logs.tar.gz using AES-256 and save the result as logs.secure.

🔸 Q5. Python Log Analysis


Question:
Write a short Python script to:
 Read a file access.log
 Extract only lines that contain the word admin
 Save the result in a new file admin_logs.txt

🔸 Q6. curl
Question:
Using curl, send a POST request to http://test.com/login with these form fields:
 username=admin
 password=1234
🔸 Q7. Python: IPv6 Count
Question:
You are given a log file with mixed IPs (IPv4 + IPv6).
Write a Python script to:
 Count how many unique IPv6 addresses appear
 Print the total number

✅ Answers & Explanations


✔️A1. sed Replace IPv6
bash
CopyEdit
sed -E 's/([0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}/IPV6/g' network.txt
✅ Explanation: Matches standard IPv6 patterns using sed -E and replaces them.

✔️A2. awk Domain Mapping


bash
CopyEdit
awk '
NR==FNR { map[$1] = $2; next }
{
for (ip in map) {
gsub(ip, map[ip])
}
print
}
' dns.txt servers.txt
✅ Explanation: First file builds IP→Domain map, second file uses gsub to replace.

✔️A3. Cron Job


bash
CopyEdit
*/15 * * * * /home/student/backup.sh
✅ Explanation: Runs every 15 minutes, every hour, daily.

✔️A4. Encrypt File


bash
CopyEdit
openssl enc -e -aes256 -in logs.tar.gz -out logs.secure
✅ Explanation: -e encrypts using AES-256, input and output files provided.

✔️A5. Python: Filter Logs


python
CopyEdit
with open("access.log") as infile, open("admin_logs.txt", "w") as outfile:
for line in infile:
if "admin" in line:
outfile.write(line)
✅ Explanation: Reads line by line and writes matches to new file.

✔️A6. curl POST Request


bash
CopyEdit
curl -X POST -d "username=admin&password=1234" http://test.com/login
✅ Explanation: -d adds form data, default method is POST when -d is used.

✔️A7. Python: Count Unique IPv6


python
CopyEdit
import re

ipv6_set = set()

with open("access.log") as f:
for line in f:
match = re.findall(r'([0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}', line)
for m in match:
ipv6_set.add(line.strip())

print("Total unique IPv6:", len(ipv6_set))


✅ Explanation: Uses regex to match IPv6 and adds unique ones to a set.

🏁 Let Me Know If You Want:


 A PDF version of this quiz
 More questions with tar, sed, awk loops, JSON parsing
 Practice questions with multiple files or mixed logs
Do you want me to prepare a second quiz with more awk, JSON, or automation questions?
Q1. AWK + Array + Loop
You are given a file called students.csv with the following format:
pgsql
CopyEdit
ID,Name,Grade1,Grade2,Grade3
101,Amal,75,80,90
102,Salem,65,55,40
103,Lina,88,90,92
Task:
Write an awk script that does the following:
 For each student, calculate the average grade.
 If the average is less than 60, print: ID Name FAIL
 Otherwise, print: ID Name PASS
📄 Expected Output:
CopyEdit
101 Amal PASS
102 Salem FAIL
103 Lina PASS

🔸 Q2. Python Log Cleaner + JSON Output


You have a web log file web.log that contains various types of HTTP requests:
pgsql
CopyEdit
[INFO] 200 OK /index.html
[ERROR] 403 Forbidden /admin
[WARNING] 404 Not Found /missing
[INFO] 302 Redirect /login
Task:
Write a Python script that:
 Extracts only the status codes and URLs (e.g., 200 /index.html)
 Saves them into a list of dictionaries
 Exports the list into a JSON file called cleaned.json
📄 Expected cleaned.json Output:
json
CopyEdit
[
{"status": "200", "url": "/index.html"},
{"status": "403", "url": "/admin"},
{"status": "404", "url": "/missing"},
{"status": "302", "url": "/login"}
]

🔸 Q3. sed IPv4 Cleaner + Count


You are given a file access.txt containing IPv4 addresses mixed with text:
nginx
CopyEdit
Login from 192.168.1.1
Failed login from 10.0.0.2
10.0.0.2 attempted again
Ping to 8.8.8.8 successful
Task:
Write a small bash script using sed and sort | uniq -c that:
 Replaces all IPv4 addresses with the word IP
 Counts how many times each line occurs (after replacement)
 Outputs the result to cleaned_access.txt
📄 Expected Output in cleaned_access.txt:
pgsql
CopyEdit
2 Failed login from IP
1 Login from IP
1 Ping to IP successful

✅ Answer Key & Explanations


✔️A1. AWK – Student Pass/Fail Script
bash
CopyEdit
awk -F, 'NR>1 {
avg = ($3 + $4 + $5)/3
if (avg < 60)
print $1, $2, "FAIL"
else
print $1, $2, "PASS"
}' students.csv
✅ Explanation:
 NR > 1 skips the header.
 $3, $4, $5 are the grades.
 Calculates average and prints based on condition.

✔️A2. Python – Log Extract to JSON


python
CopyEdit
import json
import re

logs = []

with open("web.log") as f:
for line in f:
match = re.search(r'\[(INFO|ERROR|WARNING)\] (\d{3}) .* (/.*)', line)
if match:
status = match.group(2)
url = match.group(3)
logs.append({"status": status, "url": url})

with open("cleaned.json", "w") as outfile:


json.dump(logs, outfile, indent=2)
✅ Explanation:
 Uses regex to extract status and URL.
 Adds them to a list of dictionaries.
 Dumps JSON to a file.

✔️A3. sed + uniq – IPv4 Replacement and Count


bash
CopyEdit
#!/bin/bash
# Script Name: clean_ipv4.sh

sed -E 's/([0-9]{1,3}\.){3}[0-9]{1,3}/IP/g' access.txt | sort | uniq -c >


cleaned_access.txt
✅ Explanation:
 Replaces all IPv4 with IP
 Sorts the lines
 Uses uniq -c to count repeated lines

Want More?
Would you like a third quiz set focused on:
 Socket programming
 curl headers
 JSON parsing + error handling
 or combining awk, sed, and Python?
Let me know — I can generate realistic exam-style scenarios tailored to your topics.
Q1. Python Socket Server & Client
You need to create a simple Python TCP server and client.
Task:
 Write a Python TCP server script that:
o Listens on localhost and port 12345
o Accepts a connection from a client
o Receives a message, prints it, and sends back "ACK" to client
o Closes the connection
 Write a Python TCP client script that:
o Connects to the server at localhost:12345
o Sends the message "Hello Server"
o Receives the response and prints it

🔸 Q2. Python HTTP GET Request


You want to fetch data from a website and print response details.
Task:
 Write a Python script that:
o Sends a GET request to https://httpbin.org/get
o Prints the status code
o Prints the response headers line by line
o Prints the response body as text

🔸 Q3. cURL: POST with Custom Header


You want to test sending JSON data with an authorization token.
Task:
 Write a curl command that:
o Sends a POST request to https://httpbin.org/post
o Sends JSON data: { "user": "test", "pass": "123" }
o Adds a custom header: Authorization: Bearer abc123token
o Prints the full response headers and body

✅ Solutions & Explanations


✔️A1. Python TCP Server
python
CopyEdit
# server.py
import socket

# Create socket object


server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Bind to localhost and port 12345


server_socket.bind(('localhost', 12345))

# Listen for incoming connections (max 1 client)


server_socket.listen(1)
print("Server listening on port 12345...")

conn, addr = server_socket.accept()


print(f"Connected by {addr}")

# Receive message from client (1024 bytes max)


data = conn.recv(1024)
print("Received from client:", data.decode())

# Send acknowledgement
conn.sendall(b"ACK")

# Close connection
conn.close()
server_socket.close()

✔️A1. Python TCP Client


python
CopyEdit
# client.py
import socket

# Create socket object


client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# Connect to server on localhost and port 12345


client_socket.connect(('localhost', 12345))

# Send message to server


client_socket.sendall(b"Hello Server")

# Receive response
response = client_socket.recv(1024)
print("Received from server:", response.decode())
# Close connection
client_socket.close()

✔️A2. Python HTTP GET Request


python
CopyEdit
import requests

response = requests.get("https://httpbin.org/get")

# Print status code


print("Status Code:", response.status_code)

# Print response headers


print("Headers:")
for header, value in response.headers.items():
print(f"{header}: {value}")

# Print response text (body)


print("\nResponse Body:")
print(response.text)

✔️A3. cURL POST with Custom Header


bash
CopyEdit
curl -X POST https://httpbin.org/post \
-H "Content-Type: application/json" \
-H "Authorization: Bearer abc123token" \
-d '{"user": "test", "pass": "123"}' \
-i
 -X POST specifies method
 -H adds headers (Content-Type & Authorization)
 -d sends JSON data
 -i includes response headers in output

🎯 How to Run:
 For Q1:
o Run server.py in one terminal
o Run client.py in another terminal
 For Q2:
o Run the Python script with python script.py
 For Q3:
o Run the curl command directly in your shell

You might also like