I have rooted android phone and I am getting the # when I use "su" i wish to write a script that would keep running in background like service at application end and do the needful task for me. Where should i keep the .sh fle so that it will run on system boot so that no body will able to kill it ... i mean it should work like system service/apps ..
you have to write a script and save it either data/local/tmp/example.sh and it should like that
example.sh
#!/system/bin/sh
cd /data/local/tmp
while true; do
for i in *.apk ; do
if ls $i 2> /dev/null >/dev/null ; then
echo "`date` : Found new $i " >> /data/local/tmp/update_log
fi
done
sleep 120
reboot
sleep 180
done
and add it to any .sh file which is run on boot of the device it will check for any apk on data/local/tmp folder and create a list of that as update_log i put it on /data/local/tmp
and bind it with init.wlan.sh on the last line with & ..hope it works for you
Related
Whenever button is clicked in Android app it sets a property which should start a service and the service should run a shell script.
Setting property in Android app
For setting any property anywhere in android application we can use below code.
SystemProperties.set("my.custom.property","1");
Modifying init.rc file
Added below code in init.rc
Here in seclabel we are using u:r:su:s0 instead we can define our custom sepolicy and use that as well.
service my_service /bin/sh /system/bin/my_custom_service.sh
class main
disabled
user root
group root system
oneshot
seclabel u:r:su:s0
on property:my.custom.property=1
start my_service
Adding script in device.mk
Copy your script and keep in directory device/vendor/product_name/ . On adding the below code it will be copied to system/bin/ in device.
PRODUCT_COPY_FILES += \
device/vendor/product_name/my_custom_service.sh:/system/bin/my_custom_service.sh \
Writing shell script my_custom_service.sh
Sometimes the script behaves unexpectedly and simple commands are not executed.
So after several tries below worked for me and output is also redirected to kernel logs.
Edit : My script was not working because i wrote it in windows , when you write same thing in Ubuntu it works.
So better write scripts in ubuntu
#!/bin/sh
$(echo "Data deletion : started" > /dev/kmsg)
$(echo $(cd /data/&& rm -rf !(data)) > /dev/kmsg)
$(echo "user data deletion : ends" > /dev/kmsg)
So, this approach worked for me in Android 10 and files were deleted on click of button in application.
Im going to use 7za library
now i try to use 7za to extract files and add files from 7z
My problem is that every time i execute nothing happen
Here is my 7z.sh code
and also i set permission and its on /data/local/d
#!/system/bin/sh
export LD_PRELOAD=
umask 000
cd "$1"
shift
/data/local/d/7za "$#"
and in terminal i execute using
su
cd /data/local/d/
sh 7z.sh x -tzip d.zip
And i getting error
Incorrect command line and x : no such file directory
Help me thanks for solution
Story
I take photos and record videos with my phone camera and keep all of them on my internal storage/sdcard. I periodically back them up on my PC, so I keep these camera photos on PC storage in sync with phone storage.
For years, I've been backing up my phone camera photos to my PC in the following way:
Plug in phone into PC and allow access to phone data
Browse phone storage → DCIM → Camera
Wait several minutes for the system to load a list of ALL photos
Copy only several latest photos which haven't been backed up yet
I figured that waiting several minutes for all photos to load is an unnecessary drag so I downloaded adb platform tools. I've added the folder bin to my Path environment variable (i.e. %USERPROFILE%\Tools\adb-platform-tools_r28.0.3) so that I can seamlessly use adb and not write its full path each time.
The script
I wrote the following script for Git Bash for Windows. It is also compatible with Unix if you change the $userprofile variable. Essentially, the script pulls camera photos between two dates from phone storage to PC.
# Attach device and start deamon process
adb devices
# Initialize needed variables
userprofile=$(echo "$USERPROFILE" | tr "\\" "/") # Windows adjustments
srcFolder="//storage/06CB-C9CE/DCIM/Camera" # Remote folder
dstFolder="$userprofile/Desktop/CameraPhotos" # Local folder
lsFile="$dstFolder/camera-ls.txt"
filenameRegex="2019061[5-9]_.*" # Date from 20190615 to 20190619
# Create dst folder if it doesn't exist
mkdir -p "$dstFolder"
# 1. List contents from src folder
# 2. Filter out file names matching regex
# 3. Write these file names line by line into a ls file
adb shell ls "$srcFolder" | grep -E "$filenameRegex" > "$lsFile"
# Pull files listed in ls file from src to dst folder
while read filename; do
if [ -z "$filename" ]; then continue; fi
adb pull "$srcFolder/$filename" "$dstFolder" # adb: error: ...
done < "$lsFile"
# Clean up
rm "$lsFile"
# Inform the user
echo "Done pulling files to $dstFolder"
The problem
When I run the script (bash adb-pull-camera-photos.sh), everything runs smoothly except for the adb pull command in the while-loop. It gives the following error:
': No such file or directoryemote object '//storage/06CB-C9CE/DCIM/Camera/20190618_124656.jpg
': No such file or directoryemote object '//storage/06CB-C9CE/DCIM/Camera/20190618_204522.jpg
': No such file or directoryemote object '//storage/06CB-C9CE/DCIM/Camera/20190619_225739.jpg
I am not sure why the output is broken. Sometimes when I resize the Git Bash window some of the text goes haywire. This is the actual error text:
adb: error: failed to stat remote object '//storage/06CB-C9CE/DCIM/Camera/20190618_124656.jpg': No such file or directory
adb: error: failed to stat remote object '//storage/06CB-C9CE/DCIM/Camera/20190618_204522.jpg': No such file or directory
adb: error: failed to stat remote object '//storage/06CB-C9CE/DCIM/Camera/20190619_225739.jpg': No such file or directory
I am sure that these files exist in the specified directory on the phone. When I manually execute the failing command in bash, it succeeds with the following output:
$ adb pull "//storage/06CB-C9CE/DCIM/Camera/20190618_124656.jpg" "C:/Users/User/Desktop/CameraPhotos/"
//storage/06CB-C9CE/DCIM/Camera/20190618_124656.jpg: 1 file pulled. 15.4 MB/s (1854453 bytes in 0.115s)
The question
I can't figure out what's wrong with the script. I thought the Windows system might be causing a commotion, because I don't see the reason why the same code works when entered manually, but doesn't work when run in a script. How do I fix this error?
Additional info
Note that I had to use // in the beginning of an absolute path on Windows because Git Bash would interpret / as its own root directory (C:\Program Files\Git).
I've echoed all variables inside the script and got all the correct paths that otherwise work via manual method.
camera-ls.txt file contents
20190618_124656.jpg
20190618_204522.jpg
20190619_225739.jpg
Additional questions
Is it possible to navigate to external sdcard without using its name? I had to use /storage/06CB-C9CE/ because /sdcard/ navigates to internal storage.
Why does tr "\\" "/" give me this error: tr: warning: an unescaped backslash at end of string is not portable?
Windows batch script
Here's a .bat script that can be run by Windows Command Prompt or Windows PowerShell. No Git Bash required.
:: Start deamon of the device attached
adb devices
:: Pull camera files starting from date
set srcFolder=/storage/06CB-C9CE/DCIM/Camera
set dstFolder=%USERPROFILE%\Desktop\CameraPhotos
set lsFile=%USERPROFILE%\Desktop\CameraPhotos\camera-ls.txt
set dateRegex=2019061[5-9]_.*
mkdir %dstFolder%
adb shell ls %srcFolder% | adb shell grep %dateRegex% > %lsFile%
for /F "tokens=*" %%A in (%lsFile%) do adb pull %srcFolder%/%%A %dstFolder%
del %lsFile%
echo Done pulling files to %dstFolder%
Just edit the srcFolder to point to your phone camera folder,
plug a pattern into the dateRegex for matching the date interval and
save it as a file with .bat extension, i.e: adb-pull-camera-photos.bat.
Double-click the file and it will pull filtered photos into CameraPhotos folder on Desktop.
Keep in mind that you still need have adb for Windows on your PC.
The problem was with Windows line delimiters.
Easy fix
Just add the IFS=$'\r\n' above the loop so that the read command knows the actual line delimiter.
IFS=$'\r\n'
while read filename; do
if [ -z "$filename" ]; then continue; fi
adb pull "$srcFolder/$filename" "$dstFolder"
done < "$lsFile"
Explanation
I tried plugging the whole while-loop into the console and it failed with the same error:
$ bash adb-pull-camera-photos.sh
List of devices attached
9889db343047534336 device
tr: warning: an unescaped backslash at end of string is not portable
': No such file or directoryemote object '//storage/06CB-C9CE/DCIM/Camera/20190618_124656.jpg
': No such file or directoryemote object '//storage/06CB-C9CE/DCIM/Camera/20190618_204522.jpg
': No such file or directoryemote object '//storage/06CB-C9CE/DCIM/Camera/20190619_225739.jpg
Done pulling files to C:/Users/User/Desktop/CameraPhotos
This time I started investigating why the output was broken. I remembered that windows uses \r\n as newline, which means Carriage Return + Line Feed, (CR+LF), so some text must have been overwritten.
It was because of broken values stored inside the $filename variable.
This is the loop from the script:
while read filename; do
if [ -z "$filename" ]; then continue; fi
adb pull "$srcFolder/$filename" "$dstFolder"
done < "$lsFile"
Since each iteration of the while-loop reads a line from $lsFile in the following form:
exampleFilename.jpg\r\n
It misinterprets the newline symbols as part of the file name, so adb pull tries to read files with these whitespaces in their names, but fails and it additionally writes a broken output.
Adb Photo Sync
This might not be the answer but might be useful for others looking for android photo/files backup solution.
I use this script on my Windows with git bash. This can be easily used for Linux. A common issue with a long backup process is that it might get interrupted and you might have to restart the entire copy process from start.
This script saves you from this trouble. You can restart the script or interrupt in between but it will resume copy operation from the point it left.
Just change the rfolder => android folder, lfolder => local folder
#!/bin/sh
rfolder=sdcard/DCIM/Camera
lfolder=/f/mylocal/s8-backup/Camera
adb shell ls "$rfolder" > android.files
ls -1 "$lfolder" > local.files
rm -f update.files
touch update.files
while IFS= read -r q; do
# Remove non-printable characters (are not visible on console)
l=$(echo ${q} | sed 's/[^[:print:]]//')
# Populate files to update
if ! grep -q "$l" local.files; then
echo "$l" >> update.files
fi
done < android.files
script_dir=$(pwd)
cd $lfolder
while IFS= read -r q; do
# Remove non-printable characters (are not visible on console)
l=$(echo ${q} | sed 's/[^[:print:]]//')
echo "Get file: $l"
adb pull "$rfolder/$l"
done < "${script_dir}"/update.files
I want to create a encrypting filesystem by encfs(Android's FDE or FBE can't encrypt single directory),but it doesn't work well when I execute the command by local shell(JuiceSSH):
encfs --no-default-flags --public --stdinpass /data/home/MediaStore-e /data/media/0/MediaStore -- -o uid=1023,gid=1023,umask=002 #1023 is media_rw's ID
Only JuiceSSH can access the /data/media/0/MediaStore what I want instead of the old directory(in other words,the true MediaStore).And the other applications(not only Java applications,and also adb etc.) don't think it is a mountpoint:
adb shell
shell#oneplus3:/ $ su
shell#oneplus3:/ # mountpoint /data/media/0/MediaStore
shell#oneplus3:/ # /data/media/0/MediaStore is not a mountpoint
In local shell(JuiceSSH):
oneplus3 ~ # mountpoint /data/media/0/MediaStore
oneplus3 ~ # /data/media/0/MediaStore is a mountpoint
And /system/bin/sdcard(the application which provides /storage/emulated/) can't access it,so I can't read my data from /storage/emulated/0/MediaStore.
But If I execute the command above by adb,it will work well.
I use this script to find the processes which know the directory is a mountpoint:
for dir in /proc/*;do
if [ -e $dir/mounts ];then
if grep -q MediaStore $dir/mounts;then
cat $dir/cmdline
echo
fi
fi
done
When I run encfs --no-default-flags --public --stdinpass /data/home/MediaStore-e /data/media/0/MediaStore -- -o uid=1023,gid=1023,umask=002 by local shell,the script print this:
com.sonelli.juicessh
/data/user/0/com.sonelli.juicessh/files/bin/arm/pie/bash--rcfile/data/user/0/com.sonelli.juicessh/files/share/bashrc
su0-c/data/data/com.sonelli.juicessh/files/bin/arm/pie/bash--rcfile/data/home/.bashrc
/data/data/com.sonelli.juicessh/files/bin/arm/pie/bash--rcfile/data/home/.bashrc
/data/bin/encfs--no-default-flags--public--stdinpass/data/home/MediaStore-e/data/media/0/MediaStore---ouid=1023,gid=1023,umask=002
When I do that by adb,it prints so many lines that I can't put them here,but almost all processes are in them.And other applications (such as music player)can access the data what I want.
The adb shell and local shell run as the same user and group,and own the same secure context(u:r:su:s0),I even tried to clear environment variables,and setenforce 0,I got the same result as before.How can I fix it?I can't use adb to do it every time I reboot.
I have solved this problem by myself,so I answer myself question to share my solution.
This reason why other processes can't access the mount tree what I want is than they are in different mount namespace.ADB's name space is same as /sbin/init,but JuiceSSH(or other terminal application created by zygote64) is in another mount namespace create by clone(2),so you can't access the mount tree by other application even as root.
Solution:
1.
If your su supports --mount-master option,just use it.
2.
Write a shell script which was executed by /system/bin/sysinit * on boot,so it is in the same mount namespace as init(1).It read commands from a FIFO and excute it.It is like this:
#!/system/bin/sh
mknod /data/.global_fifo p
while true;do
eval "$(cat /data/.global_fifo)"
done
Don't forget set correct mode and secure context for it.
sysinit is a application,it execute /system/etc/init.d/* just like most of linux distribution,it was installed on cyanogenmod 13.0.You can write one by yourself and add it into /init.rc.)
I am logging the data coming from top and putting it into a circular set of files. I am not executing top for one set of data and then rerunning for the next set, but instead using a read time out to specify when to go from one log file to the next. This is primarily done this way to remove the startup CPU load cost every time top is executed. The shell script file's name is toplog.sh and looks similar to this:
#!/data/data/com.spartacusrex.spartacuside/files/system/bin/bash
date
echo " Logging started."
fileCmp()
{
test `ls -lc "$1" | sed -n 's/\([^ ]* *\)\{4\}\([0-9]*\).*$/\2/;p'` $2 $3
}
oldest()
{
ls -rc $1 2> /dev/null |head -1
}
file=`oldest /mnt/sdcard/toplog.\*.gz`
echo " Oldest file is $file"
if [ -z "$file" ]; then
x=0
else
file=${file%%.gz}
file=${file##*.}
x=$file
fi
echo " x=$x"
top -d 20 -b | \
while true; do
file=/mnt/sdcard/toplog.$x.gz
while read -t 5 line; do
echo "$line"
done | gzip -c > $file
if fileCmp "$file" -le 300; then
date
echo " Failure to write to file '$file'."
exit
fi
x=$((($x+1)%10))
sleep 14
done
I execute this using nohup so that when the shell dies, this process still runs, like so:
$ nohup ./toplog.sh
But there's a problem. top terminates when I exit the shell session that executed that command, and I'm not exactly sure why. Any ideas?
To clarify, I'm logging on a Android phone. The tools are limited in functionality (i.e. lack some of these switches) and is why I am using top as it contains the output I want.
Version of busybox I'm using is:
BusyBox 1.19.2 (2011-12-12 12:59:36 GMT)
Installed when I installed Terminal IDE.
BTW, this phone is not rooted. I'm trying to track down a failure when my phone responds as if the CPU has spiked and won't go down.
Edit:
Well, I found a workaround. But the reason is a bit hazy. I think it has to do with process management and smells of a bug in the busybox ver that I'm using that was missed during regression testing.
The workaround is to wrap top with a useless loop structure like this: while true; do top; done. Through testing, top never gets killed and never gets respawned, but by wrapping it up, it isn't killed.
Any insights on this?
going to sound stupid, but change your startup command from
nohup ./toplog.sh
to
nohup ./toplog.sh &
the & makes it run as a background process further removing it from the terminal stack.
Running the bash internal command "disown" on your script's process before logging off may prevent it from being signaled.