Harden sshd_config via python
<ol>
<li>Find line starting with "#PermitRootLogin yes" and replace with "PermitRootLogin no"</li>
<li>Append line at the bottom saying "AllowUsers user1@test.com"</li>
<li>Restart sshd daemon</li>
</ol>

<p>(My Code)</p>

<pre><code>#!/usr/bin/python3
import fileinput

for line in fileinput.input("/etc/ssh/sshd_config", inplace=True), : 
    print (line.replace("#PermitRootLogin", "PermitRootLogin no"))
</code></pre>

<p>(Error)</p>

<p>Traceback (most recent call last):
  File "./assignment4-part1.py", line 6, in 
    print (line.replace("#PermitRootLogin", "PermitRootLogin=no"))
AttributeError: 'FileInput' object has no attribute 'replace'</p>

<p>(Notes)</p>

<p>I tried different methods as seen from other posts doing find and replace line, but run into similar problems/errors.  Any guidance would be much appreciated.  I am using CentOS, and python3 is installed/updated.</p>

<p>You have a syntax error in your code.  Your <code>for</code> loop expression has an erroneous comma:</p>

<pre><code>for line in fileinput.input("/etc/ssh/sshd_config", inplace=True), : 
</code></pre>

<p>That means that you're actually iterating over a single-element tuple, containing a <code>fileinput.FileInput</code> object, rather than iterating over the object itself.</p>

<p>Remove the comma:</p>

<pre><code>for line in fileinput.input("sshd_config", inplace=True):                       
</code></pre>

<p>Two other short recommendations:</p>

<p>Don't use <code>print</code> in your loop, because <code>print</code> appends a newline, so you'll end up double-spacing your entire file.  Consider instead:</p>

<pre><code>for line in fileinput.input("sshd_config", inplace=True):                       
    sys.stdout.write(line.replace("#PermitRootLogin", "PermitRootLogin no"))              
</code></pre>

<p>Lastly, consider what will happen if your input file contains:</p>

<pre><code>#PermitRootLogin no
</code></pre>

<p>Your code will rewrite this as:</p>

<pre><code>PermitRootLogin no no
</code></pre>

<p>Which is invalid.</p>

python python-3.x