[virt-tools-list] [virt-bootstrap] [PATCH v3 18/24] Build_QCOW2_Image: Enable setting root password

Radostin Stoyanov rstoyanov1 at gmail.com
Wed Aug 2 12:08:32 UTC 2017


---
 src/virtBootstrap/utils.py | 45 +++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 45 insertions(+)

diff --git a/src/virtBootstrap/utils.py b/src/virtBootstrap/utils.py
index e9fd35e..4482f6d 100644
--- a/src/virtBootstrap/utils.py
+++ b/src/virtBootstrap/utils.py
@@ -71,6 +71,7 @@ class Build_QCOW2_Image(object):
         self.progress = kwargs['progress']
         self.uid_map = kwargs.get('uid_map', None)
         self.gid_map = kwargs.get('gid_map', None)
+        self.root_password = kwargs.get('root_password', None)
         self.fmt = 'qcow2'
         self.qcow2_files = [os.path.join(kwargs['dest'], 'layer-%s.qcow2' % i)
                             for i in range(len(self.tar_files))]
@@ -79,6 +80,19 @@ class Build_QCOW2_Image(object):
         self.create_base_qcow2_layer(self.tar_files[0], self.qcow2_files[0])
         if len(self.tar_files) > 1:
             self.create_backing_chains()
+        elif self.root_password is not None:
+            # Add base disk and launch
+            self.g.add_drive_opts(
+                self.qcow2_files[0],
+                readonly=False,
+                format=self.fmt
+            )
+            self.g.launch()
+
+        # Set root password
+        if self.root_password is not None:
+            self.set_root_password()
+
         self.g.shutdown()
 
     def create_and_add_disk(self, qcow2_file, backingfile=None,
@@ -173,6 +187,37 @@ class Build_QCOW2_Image(object):
             if new_uid != -1 or new_gid != -1:
                 self.g.lchown(new_uid, new_gid, os.path.join('/', member.name))
 
+    def set_root_password(self):
+        """
+        Set root password in the shadow file of image.
+
+        Mount the last the layer to update the shadow file with the
+        hash for the root password.
+        """
+        self.progress("Setting root password", logger=logger)
+
+        last_layer_dev = self.g.list_devices()[-1]
+        self.g.mount(last_layer_dev, '/')
+
+        if not self.g.is_file('/etc/shadow'):
+            logger.error('showfile was not found in this image')
+            return
+
+        shadow_content = self.g.read_file('/etc/shadow').split('\n')
+
+        if not shadow_content:
+            logger.error('showfile was empty')
+            return
+
+        # Note: 'shadow_content' is of type list, thus pass-by-reference
+        # is used here.
+        set_password_in_shadow_content(
+            shadow_content,
+            self.root_password
+        )
+        self.g.write('/etc/shadow', '\n'.join(shadow_content))
+        self.g.umount('/')
+
 
 def get_compression_type(tar_file):
     """
-- 
2.13.3




More information about the virt-tools-list mailing list