Full Code of marcan/takeover.sh for AI

master cc84e943ad9f cached
5 files
8.9 KB
2.4k tokens
1 symbols
1 requests
Download .txt
Repository: marcan/takeover.sh
Branch: master
Commit: cc84e943ad9f
Files: 5
Total size: 8.9 KB

Directory structure:
gitextract_42wlh427/

├── .gitignore
├── LICENSE
├── README.md
├── fakeinit.c
└── takeover.sh

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
/fakeinit


================================================
FILE: LICENSE
================================================
Copyright 2017 Hector Martin "marcan" <marcan@marcan.st>
Init code based on Rich Felker's trivial init: https://ewontfix.com/14/

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.



================================================
FILE: README.md
================================================
# takeover.sh

A script to completely take over a running Linux system remotely, allowing you
to log into an in-memory rescue environment, unmount the original root
filesystem, and do anything you want, all without rebooting. Replace one distro
with another without touching a physical console.

## WARNING WARNING WARNING WARNING

This is experimental. Do not use this script if you don't understand exactly
how it works. Do not use this script on any system you care about. Do not use
this script on any system you expect to be up. Do not run this script unless
you can afford to get physical access to fix a botched takeover. If anything
goes wrong, your system will most likely panic.

That said, this script will not (itself) make any permanent changes to your
existing root filesystem (assuming you run it from a tmpfs), so as long as you
can remotely reboot your box using an out-of-band mechanism, you *should* be OK.
But don't blame me if it eats your dog.

This script does not have any provisions for exiting *out* of the new
environment back into something sane. You *will* have to reboot when you're
done. If you get anything wrong, your machine won't boot. Tough luck.

This is not a guide for newbies. I'm deliberately not giving you commands you
can copy and paste. If you can't figure out what to do exactly without
handholding, this script is not for you.

## Compatibility

This script is designed for init systems that support the `telinit u` command to
reload the init binary. This includes sysvinit and systemd. If your init system
works a different way, you will have to adapt it, or this might not work at
all. You're on your own here.

You should always test this in a VM first. You can grab a tarball of your live
root filesystem, extract it into a VM image, get your VM up and running (boot
loader setup is left as an exercise for the reader), then try the process there
and see if it works. Hint: `mount --bind / /mnt` will get you a view of your
root filesystem on `/mnt` without any other filesystems that are mounted on top.

## Usage

You need to decide on what rescue environment you want. I recommend
[SystemRescueCD](https://www.system-rescue-cd.org/), which comes with many
useful tools (you have to loopmount the ISO and then use `unsquashfs`).
Obviously, whatever you pick has to fit into free RAM, with room to spare. If
your chosen rescue environment has `/lib/modules`, you may want to get rid of
it to save space, as its kernel modules won't be useful on the host kernel
anyway.

1. Create a directory `/takeover` on your target system and mount a tmpfs on it
2. Extract your rescue environment there. Make sure it works by chrooting into
   it and running a few commands. Make sure you do not bork filesystem
   permissions. Exit the chroot.
3. Grab a recent copy of `busybox` (statically linked) and put it in
   `/takeover/busybox`. You can find binaries
   [here](https://www.busybox.net/downloads/binaries/1.26.2-defconfig-multiarch/).
   Make sure it works by trying something like `/takeover/busybox sh`.
4. Copy the contents of this repository into `/takeover`.
5. Compile `fakeinit.c`. It must be compiled such that it works inside the
   takeover environment. If your rescue environment has `gcc`, you can just
   compile it inside the chroot: `chroot /takeover gcc /fakeinit.c -o /fakeinit`.
   Otherwise, you might want to statically link it.
6. Shut down as many services as you can on your host. `takeover.sh` will by
   default set up an SSHd listening on port 80, though you may edit this in
   the script.
7. Run `sh /takeover/takeover.sh` and follow the prompts.

If everything worked, congratulations! You may now use your new SSH session
to kill any remaining old daemons (`kill -9` is recommended to make sure they
don't try to do anything silly during shutdown), and then unmount all
filesystems under `/old_root`, including `/old_root` itself. You may want to
first copy `/old_root/lib/modules` into your new tmpfs in case you need any old
kernel modules.

You are now running entirely from RAM and should be able to do as you please.
Note that you may still have to clean up LVM volumes (`dmsetup` is your friend)
and similar before you can safely repartition your disk and install Gentoo
Linux, which is of course the whole reason you're doing this crazy thing to
begin with. 

When you're done, unmount all filesystems, `sync`, then `reboot -f` or `echo b >
/proc/sysrq-trigger` and cross your fingers.

## Further reading

I've been pointed to
[this StackExchange answer](http://unix.stackexchange.com/questions/226872/how-to-shrink-root-filesystem-without-booting-a-livecd/227318#227318)
which details how to manually perform a similar process, but using a subset of
the existing root filesystem instead of a rescue filesystem. This allows you
to keep (a new copy of) the existing init system running, as well as essential
daemons, and then go back to the original root filesystem once you're done. This
is a more useful version if, for example, you want to resize the original root
filesystem or re-configure disk partitions, but not actually install a different
distro, and you want to avoid rebooting at all.

`takeover.sh` could be extended to support re-execing a new init once you're
done. This could be used to switch to a *new* distro entirely without
rebooting, as long as you're happy using the old kernel. If you're interested,
pull requests welcome :-).


================================================
FILE: fakeinit.c
================================================
#define _XOPEN_SOURCE 700
#include <signal.h>
#include <unistd.h>
#include <sys/wait.h>

int main()
{
	sigset_t set;
	int status, i;

	for (i = 0; i < 1024; i++)
		close(i);

	if (getpid() != 1) return 1;

	sigfillset(&set);
	sigprocmask(SIG_BLOCK, &set, 0);

	for (;;) wait(&status);
}



================================================
FILE: takeover.sh
================================================
#!/bin/sh
set -e

TO=/takeover
OLD_INIT=$(readlink /proc/1/exe)
PORT=80

cd "$TO"

if [ ! -e fakeinit ]; then
    ./busybox echo "Please compile fakeinit.c first"
    exit 1
fi

./busybox echo "Please set a root password for sshd"

./busybox chroot . /bin/passwd

./busybox echo "Setting up target filesystem..."
./busybox rm -f etc/mtab
./busybox ln -s /proc/mounts etc/mtab
./busybox mkdir -p old_root

./busybox echo "Mounting pseudo-filesystems..."
./busybox mount -t tmpfs tmp tmp
./busybox mount -t proc proc proc
./busybox mount -t sysfs sys sys
if ! ./busybox mount -t devtmpfs dev dev; then
    ./busybox mount -t tmpfs dev dev
    ./busybox cp -a /dev/* dev/
    ./busybox rm -rf dev/pts
    ./busybox mkdir dev/pts
fi
./busybox mount --bind /dev/pts dev/pts

TTY="$(./busybox tty)"

./busybox echo "Checking and switching TTY..."

exec <"$TO/$TTY" >"$TO/$TTY" 2>"$TO/$TTY"

./busybox echo "Type 'OK' to continue"
./busybox echo -n "> "
read a
if [ "$a" != "OK" ] ; then
    exit 1
fi

./busybox echo "Preparing init..."
./busybox cat >tmp/${OLD_INIT##*/} <<EOF
#!${TO}/busybox sh

exec <"${TO}/${TTY}" >"${TO}/${TTY}" 2>"${TO}/${TTY}"
cd "${TO}"

./busybox echo "Init takeover successful"
./busybox echo "Pivoting root..."
./busybox mount --make-rprivate /
./busybox pivot_root . old_root
./busybox echo "Chrooting and running init..."
exec ./busybox chroot . /fakeinit
EOF
./busybox chmod +x tmp/${OLD_INIT##*/}

./busybox echo "Starting secondary sshd"

./busybox chroot . /usr/bin/ssh-keygen -A
./busybox chroot . /usr/sbin/sshd -p $PORT -o PermitRootLogin=yes

./busybox echo "You should SSH into the secondary sshd now."
./busybox echo "Type OK to continue"
./busybox echo -n "> "
read a
if [ "$a" != "OK" ] ; then
    exit 1
fi

./busybox echo "About to take over init. This script will now pause for a few seconds."
./busybox echo "If the takeover was successful, you will see output from the new init."
./busybox echo "You may then kill the remnants of this session and any remaining"
./busybox echo "processes from your new SSH session, and umount the old root filesystem."

./busybox mount --bind tmp/${OLD_INIT##*/} ${OLD_INIT}

telinit u

./busybox sleep 10

Download .txt
gitextract_42wlh427/

├── .gitignore
├── LICENSE
├── README.md
├── fakeinit.c
└── takeover.sh
Download .txt
SYMBOL INDEX (1 symbols across 1 files)

FILE: fakeinit.c
  function main (line 6) | int main()
Condensed preview — 5 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (10K chars).
[
  {
    "path": ".gitignore",
    "chars": 10,
    "preview": "/fakeinit\n"
  },
  {
    "path": "LICENSE",
    "chars": 1154,
    "preview": "Copyright 2017 Hector Martin \"marcan\" <marcan@marcan.st>\nInit code based on Rich Felker's trivial init: https://ewontfix"
  },
  {
    "path": "README.md",
    "chars": 5436,
    "preview": "# takeover.sh\n\nA script to completely take over a running Linux system remotely, allowing you\nto log into an in-memory r"
  },
  {
    "path": "fakeinit.c",
    "chars": 288,
    "preview": "#define _XOPEN_SOURCE 700\n#include <signal.h>\n#include <unistd.h>\n#include <sys/wait.h>\n\nint main()\n{\n\tsigset_t set;\n\tin"
  },
  {
    "path": "takeover.sh",
    "chars": 2182,
    "preview": "#!/bin/sh\nset -e\n\nTO=/takeover\nOLD_INIT=$(readlink /proc/1/exe)\nPORT=80\n\ncd \"$TO\"\n\nif [ ! -e fakeinit ]; then\n    ./busy"
  }
]

About this extraction

This page contains the full source code of the marcan/takeover.sh GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 5 files (8.9 KB), approximately 2.4k tokens, and a symbol index with 1 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!