Tag Archives: root password

New in virt-sysprep: Set root and user passwords

New in virt-sysprep ≥ 1.23.13 is the ability to set root and user passwords in Linux guests (previous manual method is described here).

$ virt-sysprep \
  --root-password password:123456 \
  --password joe:file:/tmp/secret -a guest.img

You shouldn’t normally specify the cleartext password on the command line, although it’s useful for testing. You should usually provide a file containing the password, ensuring that it is not readable by other users on the system (ie. mode 0600).

4 Comments

Filed under Uncategorized

Setting the root (or other) passwords in a Linux guest

I wrote this example for the CentOS Dojo on Friday (which by the way will be recorded and available on YouTube afterwards).

You can use or modify this script to change the password in /etc/shadow for root or any other user of a guest.

The $5$ causes it to use a SHA-256-encrypted password, but you can change this to $6$ to use SHA-512 (both assume you are using glibc on the host).

#!/usr/bin/perl -w

use strict;
#use Sys::Virt;
use Sys::Guestfs;

my $vm = "dojo";
my $user = "root";
my $newpw = "1234567";

my $salt;
my @chars = ("A".."Z", "a".."z", "0".."9", ".", "/");
$salt .= $chars[rand @chars] for 1..16;
my $crypted = crypt ($newpw, '$5$' . $salt . '$');

my $g = Sys::Guestfs->new ();
$g->set_trace (1);
$g->add_domain ($vm, libvirturi => "qemu:///session");
$g->launch ();
$g->mount ("/dev/fedora/root", "/");

my @shadow = $g->read_lines ("/etc/shadow");
s/^root:.*?:/root:$crypted:/ foreach @shadow;

$g->write ("/etc/shadow", join ("\n", @shadow) . "\n");
$g->chmod (0, "/etc/shadow");

$g->touch ("/.autorelabel");

Leave a comment

Filed under Uncategorized

Tip: replace text strings in a file using guestfish

virt-edit has a handy -e option that lets you do replacements on files. For example this wipes out your root password:

virt-edit domname /etc/passwd -e 's/^root:.*?:/root::/'

How can you do the same thing from guestfish or the libguestfs API?

There’s no support for this operation directly in the API, but you can download the file, use sed/perl/whatever on it locally, and upload it, and that is essentially the same thing that virt-edit is doing.

Here’s how to do that easily in guestfish:

$ guestfish --rw -i -d domname
><fs> download /etc/passwd /tmp/passwd
><fs> ! sed 's/^root:[^:]\+:/root::/' /tmp/passwd > /tmp/passwd.new
><fs> upload /tmp/passwd.new /etc/passwd

In guestfish, ! before a command runs a local command.

3 Comments

Filed under Uncategorized